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?
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.
Yes, we can declare a constructor as private.
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.
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.
There are two ways:
public
or protected
.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With