This is the code:
class TestA
{
protected:
int test=12;
public:
TestA() {
cout << "test a: " << test << endl;
}
~TestA() {
}
};
class TestB : public TestA
{
public:
TestB(TestA *testA) {
cout << "test b: " << testA->test;
}
~TestB() {
}
};
int main ()
{
TestA *pTestA=new TestA();
TestB *pTestB=new TestB(pTestA);
}
I'm trying to access of a protected
member using a pointer pointing to a TestA
type object (thus, an instance of TestA
). TestB
is also derived from TestA
Why I can't access to it? Is it accessible only "within" the class where I need it? Not outside using pointer/direct declarations?
When public inherite from the base class, its protected members become the derived class' protect members, which could be accessed in derived class' member functions. But they could only be accessed through the derived class itself (and its derived classes), can't be accessed through the base class. So you can't access member
test
via pointer ofTestA
, but it'll be fine to access it via pointer ofTestB
.The standard gives some illustrative samples for this. $11.4/1 Protected member access [class.protected]:
(Only keep a part of the example code)
I'm not sure about your design's intent, making
TestB
friend ofTestA
would be a straightforward solution.Concept of accessibility of class members by WORLD is applicable here. WORLD can access only public members of class irrespective of how they are created/derived.
Consider the example below: