C ++ can't subclass because of parent protected constructor?
This is the code I find it hard to understand:
class A
{
protected:
int _i;
A () : _i(0) { }
~A () { }
};
class B: public A
{
public:
A *_pa;
B() : A(), _pa(new A())
{ }
~B ()
{
delete _pa;
}
};
int main ()
{
A a; //ERROR
B b; //ERROR
}
When I try to instantiate a class of a type, A
I get an error because it's constructor is protected. But why can't I create a type class B
? The class has access to protected members A
(including the ctor), so it must compile.
source to share
Your error is in the new A
inside of the constructor B
, not on the super constructor call.
Let me explain to you how it works protected
. When you have a class B
that is a subclass A
, it does not have access to protected elements A
, it has access to protected elements A
when working with a reference B
.
To show your thought:
#include <iostream>
class A {
protected:
int a;
};
class B : public A {
public:
void do_it(A* a) {
std::cout << a->a << std::endl; //ERROR
}
void do_it(B* a) {
std::cout << a->a << std::endl; //VALID CODE
}
};
My guess is that the reason for this behavior is that if you have a third class C
that also has access to A
protected members, it probably isn't a good idea that someone else will change those protected values.
source to share
In the constructor, the constructor B
is called A
. Since the constructor A
is protected, calling the constructor A
in the constructor B
gives an error. There is A
also a destructor in the protected area . When a B
destructor is called , its base class's destructor ( A
) is also called . Since the destructor A
is protected, another error occurs. If you cross out the constructor A
from the constructor B
, an error will still be displayed. But you can get rid of the errors by sharing the destructor A
.
public:
~A () { }
This conclusion, drawn by checking for errors given by code blocks, but seems to be wrong. Removing _pa (new A ()) is the exact solution. @ AndréPuel's answer is more correct.
source to share