- 1

Friend function

For what is used friend function ? Example in real code pls ...

3rd Dec 2016, 10:36 AM
Martin Horníček
Martin Horníček - avatar
3 Respostas
+ 2
try this code :- #include <iostream> using namespace std; class MyClass { public: MyClass() { regVar = 0; }; private: int regVar; friend void someFunc(MyClass &obj); // Declairing friend function from outside the // class and pass the class object reference // as parameter to access its private variables }; void someFunc(MyClass &obj) { // Now writing the function code (outside the class ) obj.regVar = 42; // wich will take the class object and change its cout << obj.regVar; // private variable and print it } int main() { MyClass obj; someFunc(obj); }
5th Dec 2016, 11:31 PM
Bashar
Bashar - avatar
0
it enables you to access The private member data directly .. class student { private: int x; int y; }; friend add(x,y) { int sum=0; sum=xx+yy; }
5th Dec 2016, 1:11 AM
Ahmed Mansy
Ahmed Mansy - avatar
0
sorry but it is not valid code... :(
5th Dec 2016, 1:26 AM
Martin Horníček
Martin Horníček - avatar