#include <iostream>
using namespace std;
class A
{
protected:
int a;
};
class B : public A
{
public:
int func(A* p)
{
cout << p->a;
}
};
I really cannot understand why I cant access to ‘a’ by ‘p->a’.
Is there anyway to access p’s member ‘a’ in class B, without changing ‘protected’ to ‘public’?
On this topic, the C++03 standard states (emphasis mine):
What you are doing here, however, is trying to access through a pointer to the base class, which is illegal. If you change the signature to
you will find that it now compiles normally.
This is also the reason why you can access
awithout trouble from insideclass B: the access is made through the implicit pointerthis, which is of typeB*(the derived class again). If you tried this:You would find that it won’t compile, for the very same reason.
The converse also applies: if you downcast the pointer
pto aB*you can access theprotectedmember just fine: