I am confused: I thought protected data was read/writable by the children of a given class in C++.
The below snippet fails to compile in MS Compiler
class A
{
protected:
int data;
};
class B : public A
{
public:
B(A &a)
{
data = a.data;
}
};
int main()
{
A a;
B b = a;
return 0;
}
Error Message:
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.30729.01 for 80x86
Copyright (C) Microsoft Corporation. All rights reserved.
demoFail.cpp
demoFail.cpp(12) : error C2248: 'A::data' : cannot access protected member declared in class 'A'
demoFail.cpp(4) : see declaration of 'A::data'
demoFail.cpp(2) : see declaration of 'A'
What am I doing wrong?
According to TC++PL, pg 404:
Of course, here's an easy way to fix this for your case:
You just shouldn't copy an
A
object in aB
constructor. The intention is to leave the initialization ofA
's members to it's own constructor:The C++ Standard says about protected non-static members at
11.5/1
In addition to fixing things mentioned earlier by others (constructor of
B
is private), i think rlbond's way will do it fine. However, a direct consequence of the above paragraph of the Standard is that the following is possible using a member pointer, which arguably is a hole in the type system, of courseOf course, this code is not recommended to do, but shows that you can access it, if you really need to (I've seen this way being used for printing out a
std::stack
,std::queue
,std::priority_queue
by accessing its protected container memberc
)The constructor of B is private. If you do not specify anything, in a class, the default modifier is private (for structs it is public). So in this example the problem is that you cannot construct B. When you add public to constructor B anoter problem arises:
B has the right to modify the part of A it derives from but not another A like in this case.
You could do following: