简体   繁体   中英

I Inherited a constructor using private, Why am I still be able to access it from main function?

#include <iostream>
using namespace std;

class base{
public:
    int i;
    base(){
    i=1;
    cout<<"Base Constructor";
    }
};

class derived: private base{
    public:
    derived(){
    i=2;
    cout<<"Derived constructor";
    }
};


int main(){ 
derived c;
return 0;
}

For the above code why am I getting the output as "Base ConstructorDerived Constructor" even though I inherited using private?

Why am I still be able to access it from main function?

You aren't.

Your main function accesses derived 's constructor, which it has access to.

And derived 's constructor accesses base 's constructor, which it has access to.

A constructor automatically initializes the base classes and the members before executing the body of the constructor. Private inheritance doesn't change that. It just makes the base part of the class not accessible outside the class. Since it is the derived class constructor that is calling the base class constructor, the private inheritance doesn't restrict what it can do.

What you mean to do is make the constructor of the base class protected . Then only derived classes can use it:

class base
{
protected:
    base() : i(1) { }
private:
    int i;
};

class derived : private base
{
public:
    derived() : base() { }
};

int main()
{ 
    // base b;  // error: inaccessible constructor base::base()
    derived d;  // fine
}

A somewhat popular pattern is also to make the destructor protected. You get the point, though.

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