Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 600
nitin_cherian Avatar asked Mar 24 '12 12:03

nitin_cherian


People also ask

Can base class access derived class private?

Private members of the base class cannot be used by the derived class unless friend declarations within the base class explicitly grant access to them.

Can a base class constructor be private?

Yes, we can declare a constructor as private.

When we inherit base class privately by the derived class then?

With private inheritance, public and protected member of the base class become private members of the derived class. That means the methods of the base class do not become the public interface of the derived object. However, they can be used inside the member functions of the derived class.

What if parent class constructor is private?

Default Constructor(No argument constructor) : In this case default constructor will automatically try to call the parent class constructor : this will fail since parent class constructor is private. 2.


2 Answers

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
like image 146
Nawaz Avatar answered Sep 28 '22 05:09

Nawaz


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.
like image 42
Oliver Charlesworth Avatar answered Sep 28 '22 04:09

Oliver Charlesworth