Instantiate a derived class object, whose base class ctor is private

nitin_cherian picture nitin_cherian · Mar 24, 2012 · Viewed 13.5k times · Source

How to instantiate a derived class object, whose base class ctor is private?

Since the derived class ctor implicitly invokes the base class ctor(which is private), the compiler gives error.

Consider this example code below:

#include <iostream>

using namespace std;

class base
{
   private:
      base()
      {
         cout << "base: ctor()\n";
      }
};

class derived: public base
{
   public:
      derived()
      {
         cout << "derived: ctor()\n";
      }
};

int main()
{
   derived d;
}

This code gives the compilation error:

accessing_private_ctor_in_base_class.cpp: In constructor derived::derived()': accessing_private_ctor_in_base_class.cpp:9: error:base::base()' is private accessing_private_ctor_in_base_class.cpp:18: error: within this context

How can i modify the code to remove the compilation error?

Answer

Nawaz picture Nawaz · Mar 24, 2012

There are two ways:

  • Make the base class constructor either public or protected.
  • Or, make the derived class a friend of the base class. see demo