I have a doubt with this code ( it is a question into a test so I don't need to change ):
class X {
protected:
int v;
};
class Y : protected X {
public:
Y() : v(0) {}
};
int main()
{
Y *y = new Y();
cout << y->v;
delete y;
return 0;
}
I was quite sure that it was good because the v member of X was accessible from Y because Y was the subclass of a protected Class which has a protected member ( v ) but I have a compilation error. Can someone help me to understand? thanks!
There are at least two problems.
The first one is that the class definitions
are ijll-formed. From the C++17 Standard( 15.6.2 Initializing bases and members ):
That is you may not use the non-static member
vof the base classXas an initializing member in the ctor initialization of the classY:The second problem is that as the data member
vis protected in the derived classYthen you may not directly access it outside the class as you are doingEither make the data member public or create a public member function that will return the value of the data member
vor a constant reference to the data member.