// an abstract base class
class CStateBase
{
virtualint Update() =0;
}
// an inherited class from the abstract base class
class CStateTitle: public CStateBase
{
int Update() {return 0;}
}
// the main class
class CApplication
{
CStateBase *m_StateCur;
int foo();
public:
friendclass CStateBase;
friendclass CStateTitle; // friends to both classes
}
int CApplication::foo()
{
m_StateCur = new CStateTitle;
m_StateCur->Update(); //compile error, cannot access private member
}
As you can see, I have an abstract base class and another class that inherits from it. The main class dynamically allocates the inherited class and tries to call its method Update(), however it produces a compile error saying it cannot access private member of CStateTitle, even though the main class is friends to both. Can someone explain why this is and if there's a fix for it other than making the Update() method public? Thanks.
You're making CStateBase and CStateTitle friends of CApplication. That is, They can access private members in CApplication.
Not the other way around.
You need to make CApplication a friend of CStateBase and CStateTitle:
1 2 3 4 5 6 7 8 9 10 11 12 13
// an abstract base class
class CStateBase
{
friendclass CApplication;
virtualint Update() =0;
}
// an inherited class from the abstract base class
class CStateTitle: public CStateBase
{
friendclass CApplication;
int Update() {return 0;}
}