Friendship with method of other class in other File
-
I have the file configuration below showed; All in independent files.
I would like to give friendship only to "void myClass::print() method" from "myClass" and not to the full "myClass" object.Please, somebody know how to replace "friend myClass"; for "friend void myClass::print()"
Thanks in advance
//mysubclass.h #ifndef MYSUBCLASS_H_ #define MYSUBCLASS_H_ class myClass; //forward declaration is needed class mySubClass { int i; friend myClass; //<-- I would like to replace it for any like friend void myClass::print() }; #endif
//myclass.h #ifndef MYCLASS_H_ #define MYCLASS_H_ class myClass { mySubClass msc; public void print(); }; #endif
//myclass.cpp #include "mysubclass.h" void myClass::print() { std::cout << msc.i << std::endl; }
-
I have the file configuration below showed; All in independent files.
I would like to give friendship only to "void myClass::print() method" from "myClass" and not to the full "myClass" object.Please, somebody know how to replace "friend myClass"; for "friend void myClass::print()"
Thanks in advance
//mysubclass.h #ifndef MYSUBCLASS_H_ #define MYSUBCLASS_H_ class myClass; //forward declaration is needed class mySubClass { int i; friend myClass; //<-- I would like to replace it for any like friend void myClass::print() }; #endif
//myclass.h #ifndef MYCLASS_H_ #define MYCLASS_H_ class myClass { mySubClass msc; public void print(); }; #endif
//myclass.cpp #include "mysubclass.h" void myClass::print() { std::cout << msc.i << std::endl; }
@Josz I'm not sure if C++ lets you do that exactly. How about https://msdn.microsoft.com/en-us/library/465sdshe.aspx#Class members as friends ?
-
I have the file configuration below showed; All in independent files.
I would like to give friendship only to "void myClass::print() method" from "myClass" and not to the full "myClass" object.Please, somebody know how to replace "friend myClass"; for "friend void myClass::print()"
Thanks in advance
//mysubclass.h #ifndef MYSUBCLASS_H_ #define MYSUBCLASS_H_ class myClass; //forward declaration is needed class mySubClass { int i; friend myClass; //<-- I would like to replace it for any like friend void myClass::print() }; #endif
//myclass.h #ifndef MYCLASS_H_ #define MYCLASS_H_ class myClass { mySubClass msc; public void print(); }; #endif
//myclass.cpp #include "mysubclass.h" void myClass::print() { std::cout << msc.i << std::endl; }
-
see
https://www.geeksforgeeks.org/friend-class-function-cpp/regards
karl-heinz -
@karlheinzreichel solution requires
mySubClass
to know the full definition ofmyClass
. You can't just pre-declareclass myClass; //forward declaration is needed
An alternative is
class FriendHelper{ public: static void actualPrint(myClass& sender); };
now move the body of
void print();
inside the body ofactualPrint
and change it tovoid print() {FriendHelper::actualPrint(*this);}
No you can make
FriendHelper
a friend of bothmyClass
andmySubClass