简体   繁体   中英

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?

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM