Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

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?

like image 616
leo Avatar asked Oct 22 '25 07:10

leo


2 Answers

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
    }
};
like image 144
songyuanyao Avatar answered Oct 23 '25 19:10

songyuanyao


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.

like image 21
Remy Lebeau Avatar answered Oct 23 '25 19:10

Remy Lebeau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!