[C++] Friend of Class Inaccessible

Hi, I have a class that has a function that dynamically allocates a friend class and tries to access one of its private methods.

I'll simplify the code to show only what's relevant for my problem:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// an abstract base class
class CStateBase
{
  virtual int 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:
    friend class CStateBase;
    friend class 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.
Last edited on
You have friendship backwards.

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
{
  friend class CApplication;
  virtual int Update() =0;
}

// an inherited class from the abstract base class
class CStateTitle: public CStateBase
{
  friend class CApplication;
  int Update() {return 0;}
}

Much appreciate the quick response, works like a charm.
Topic archived. No new replies allowed.