Table of Contents
Friend Function in C ++ is easier to understand when the core ideas are paired with practical examples. The sections below explain the topic clearly, highlight useful steps, and point out details that can prevent common errors.
The friend function in C ++ of a class is defined outside of that class scope, but it has access to all private and protected members of that class. Even if the prototypes for friend functions appear in the class definition, friend functions are not member functions.
A friend can be a function, a function pattern, or a member function, or a class or a class template, in this case, the entire class and all its members are friends.
To declare a function of friend function of a class, precede that function prototype in class definition with friend keyword in C ++, as follows:
class Box { double chieurong ; public : double chieudai ; friend void inChieuRong ( Box box ); void setChieuRong ( double rong ); };
To declare all member functions of the LopMai class as friend type of LopMot class, put a following declaration in the definition of LopMot class:
friend class LopHai ;
You consider the following program:
#include using namespace std ; class Box { double chieurong ; public : friend void inChieuRong ( Box box ); void setChieuRong ( double rong ); }; // phan dinh nghia ham thanh vien void Box :: setChieuRong ( double rong ) { chieurong = rong ; } // Ghi chu: inChieuRong() khong la ham thanh vien cua bat cu class nao. void inChieuRong ( Box box ) { /* Boi vi, ham inChieuRong() la ham friend cua Box, do vay no co the truc tiep truy cap bat cu thanh vien nao cua class nay */ cout << "Chieu rong cua box la: " << box . chieurong << endl ; } // ham main cua chuong trinh int main ( ) { Box box ; // thiet lap chieurong cua box, khong su dung ham thanh vien box . setChieuRong ( 25.3 ); // su dung ham friend de in chieu rong. inChieuRong ( box ); return 0 ; }
Next lesson: Inline function in C ++
Frequently Asked Questions
What is Friend Function in C ++?
The friend function in C ++ of a class is defined outside of that class scope, but it has access to all private and protected members of that class.
Why is Friend Function in C ++ important?
A clear understanding of Friend Function in C ++ helps you make informed decisions, avoid common mistakes, and use the relevant tools or techniques more effectively.
How should beginners approach Friend Function in C ++?
Start with the fundamental concepts, follow the examples step by step, and test each change in a safe environment before applying it to important systems or data.
Was this article helpful?
Your feedback helps us improve.
Reader Comments 0
Sign in with email or Google to join the discussion.