14

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?

nitin_cherian
  • 6,405
  • 21
  • 76
  • 127

3 Answers3

20

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
Nawaz
  • 353,942
  • 115
  • 666
  • 851
2

You can't inherit from a base-class whose only constructor is private.1

So make the base-class constructor public/protected, or add another base-class constructor.


1. Unless, as Nawaz points out, you are a friend of the base class.
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
1

You can't. That's usually the reason to make the only c'tor private, disallow inheritance.

selalerer
  • 3,766
  • 2
  • 23
  • 33