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

leo*_*leo 2 c++ protected

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();
}
Run Code Online (Sandbox Code Playgroud)

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?

son*_*yao 6

protected成员可以从派生类访问,但只能通过派生类访问。

protected类的成员只能访问

  1. ...
  2. and friends (until C++17)该类的任何派生类的成员,但仅当访问受保护成员的对象的类是该派生类或该派生类的派生类时:

所以即使在派生类的成员函数中也不能创建基类的独立对象。

换句话说protected,派生类当前实例的protected成员可以访问,而独立基类的成员则不能。例如

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
    }
};
Run Code Online (Sandbox Code Playgroud)