Search code examples
c++inheritancecompiler-errorsprivate-constructor

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


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?


Solution

  • 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