Through this video we are learning about friend function in c++
Function is defined as a friend function in c++ , then the private and protected data member can be accessed using the function .
By using this keyword compiler knows that this is friend
function
Characteristic of Friend function in c++
- The function is not in the scope which is declared as friend function
- It is not called using the object
- It can be Invoked like normal function without using the object
- It can not accessed the member name directly
- It is accessed by function name dot member operator with the member name
- It can declared in private , protected or public function.
C++ friend function Example
- #include <iostream>
- using namespace std;
- class Box
- {
- private:
- int length;
- public:
- Box(): length(0) { }
- friend int printLength(Box); //friend function
- };
- int printLength(Box b)
- {
- b.length += 10;
- return b.length;
- }
- int main()
- {
- Box b;
- cout<<"Length of box: "<< printLength(b)<<endl;
- return 0;
- }
Output :
Length of box: 10
In the above Code you will see that what is friend function and how
friend function works.
This article is Contributed by Mohd Abuzar . If you like Code with abuzar or want to give
more suggestion or write something you can mail at abuzar.abuzar.mohd325@gmail.com
Please write comment if you find anything incorrect .
0 Comments
Do not Comment and any spam text