简体   繁体   中英

C++: Why Protected Constructor Cannot be Accessed in the Derived Class?

Protected member is supposed to be accessible from derived class. Then, why I got the compiling error in the code below?

class A {
protected:
    A() {};
};

class B : public A {
public:
    void g() { 
        A a; // <--- compiling error: "Protected function A::A() is not accessible ...". Why?
    }
};


int main() {
    B b;
    b.g();
}

I noticed there is a related post, but the class there is a template class. Mine is just a "regular" class.

Why the derived class cannot access protected base class members?

protected members could be accessed from derived class, but only when through the derived class.

A protected member of a class is only accessible

  1. ...
  2. to the members and friends (until C++17) of any derived class of that class, but only when the class of the object through which the protected member is accessed is that derived class or a derived class of that derived class:

So you can't create an indpendent object of base class even in member functions of derived class.

Put it in another way, the protected members of the current instance of derived class could be accessed, but protected members of independent base class can't. Eg

class A {
protected:
    int x;
public:
    A() : x(0) {}
};

class B : public A {
public:
    void g() {
        this->x = 42; // fine. access protected member through derived class
        A a;
        a.x = 42;     // error. access protected member through base class
    }
};

Protected member is supposed to be accessible from derived class.

Yes, but only when accessed via the this pointer. Not when accessed on a complety separate object. Which you are trying to do, when B::g() tries to construct a new A object.

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