I Inherited a constructor using private, Why am I

2019-06-05 20:36发布

#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?

标签: c++ oop object
3条回答
可以哭但决不认输i
2楼-- · 2019-06-05 21:31

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.

查看更多
倾城 Initia
3楼-- · 2019-06-05 21:36

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.

查看更多
做自己的国王
4楼-- · 2019-06-05 21:36

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.

查看更多
登录 后发表回答