Example of Friend function cannot be invoked with the object – C++
The friend function cannot be invoked with the object as the friend function is not in the scope of that class.
The program shows an error because the Friend function cannot be invoked with the object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> using namespace std; class one { private: int n1=1; public: friend int add(one); }; int add(one object1) { return (object1.n1 + 1); } int main() { one object1; object1.add(); cout<<"Sum: "<< add(object1); return 0; } |
Correct program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> using namespace std; class one { private: int n1=1; public: friend int add(one); }; int add(one object1) { return (object1.n1 + 1); } int main() { one object1; cout<<"Sum: "<< add(object1); return 0; } |