C ++ simple inheritance problem

#include <iostream> using namespace std; class A { protected: int a; }; class B : public A { public: int func(A* p) { cout << p->a; } }; 

I really don't understand why I cannot access 'a' on 'p-> a'.

Is there any access to the p member of 'a' in class B without changing 'protected' to 'public'?

+4
source share
3 answers

In this topic, the standard state of C ++ 03 (my attention):

11.5 Access to protected member

1 When a friend or member function of a derived class refers to a protected non-static member function or a protected non-static data element of the base class, access control is applied in addition to those described earlier in clause 11. Except in cases where a pointer to the element is generated (5.3.1 ), access should be through a pointer to a link, a link to an object or a class object (or any class derived from this class) (5.2.5).

What you are doing here is trying to access through a pointer to a base class, which is illegal. If you change the signature to

 int func(B* p) // instead of A* 

You will find that it now compiles normally.

This is also the reason that you can access a from within class B without any problems: access is via the implicit this pointer, which is of type B* (derived class again). If you tried this:

 A* parent = static_cast<A*>(this); int x = parent->a; // Does not compile! 

You will find that it will not compile for the same reason.

The opposite also applies: if you omit the pointer p to B* , you can access the protected element simply:

 class A { public: // Added virtual destructor so that the class acquires a vptr, // making dynamic_cast possible. virtual ~A() {}; protected: int a; }; class B : public A { public: int func(A* p) { // Now if we downcast p to B* we can access a just fine // Of course if p does not actually point to a B, the // program will have undefined behavior int x = dynamic_cast<B*>(p)->a; } }; 
+9
source

Using p->a will allow you to access the public variables of A. Since a is a protected variable, you should use cout << a , since a inherited in class B.

I think you could use cout << p->a in the friend ing class.

Or by pointing to a pointer to B instead of a pointer to a , as Jon pointed out.

+2
source

Ah, that’s a good question. First, let me say that B NOT a friend of A and therefore does not have access to A private (or protected) through the representation of the β€œA” object. Although we are in class B , we cannot just look at A privates (or protected).

HOWEVER, B has A And he has access to him, as he is declared a protected member of A But the only way to see int a inside B is to get it from the B representation of the object.

+1
source

All Articles