0

If I have two classes:

class worker
{
   Top *mp_parent;

   worker(Top *parent) : mp_parent(parent) {};

   int doSomeWork()
   {
      int i = mp_parent->privateFunction(); // This is the function I want to call
   }
}

class Top
{
   private:
   worker m_Worker;

   int privateFunction() {return 1;}

}

Where Top class contains a instance of worker class. When worker is instantiated, a pointer to the parent class is passed in. Later, the function doSomeWork() is called which needs to get a value from the parent, so it calls mp_parent->privateFunction().

What is the best way to achieve this? - I don't really want to make privateFunction() a public function if I can avoid it, but it does not work as it is because it is private :o

Are there any other options?

code_fodder
  • 15,263
  • 17
  • 90
  • 167

2 Answers2

1

Maybe you can use the 'friend' keyword:

class worker
{
   Top *mp_parent;

   worker(Top *parent) : mp_parent(parent) {};

   int doSomeWork()
   {
      int i = mp_parent->privateFunction(); // This is the function I want to call
   }
}

class Top
{
   friend class worker;
   private:
   worker m_Worker;

   int privateFunction() {return 1;}

}
0

This is a classic use of friends:

class Top
{
   private:
   friend class Worker;
   worker m_Worker;

   int privateFunction() {return 1;}

}

You should be thoughtful about making friends, and consider whether you can redesign to avoid them, but sometimes it makes sense.

Jay Miller
  • 2,184
  • 12
  • 11