leo
leo

Reputation: 437

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?

Upvotes: 4

Views: 1045

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 595782

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.

Upvotes: 0

songyuanyao
songyuanyao

Reputation: 172894

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. E.g.

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
    }
};

Upvotes: 8

Related Questions