Short answer: By declaring m_Pa
private, you are saying that only class A
should be able to modify it. So you cannot alter its value using methods of class B
.
Longer answer: In C++ (and most other object oriented programming languages), you not only declare the type of a member, but also its visibility (public
, protected
and private
). This allows you to enfore encapsulation of data: You only expose an interface, but you do not let clients of your class modify its internals directly.
In your concrete example, I would create accessors
Foo* getPa() {
return m_Pa;
}
void setPa(Foo* Pa) {
m_Pa = Pa;
}
in class A
and use them in class B
to modify m_Pa
. If you would like class B
(but not unrelated classes) to be able to modify m_Pa
declare getPa()
and setPa()
in a protected:
section of your class; if you would like any client to modify them declare them in a public:
section. Especially in the later case you need to start worrying about object ownership, i.e. which object is responsible for deleting the object stored in m_Pa
which is created in the constructor. A practical solution to this problem is to use smart pointers, see for instance boost's implementation.
A note on terminology: "Overriding" a member in C++ usually refers to giving a new implementation of a virtual
member function. So if your class A
has a method
virtual void doIt()
then a member of the same type in class B
overrides the implementation of A
's doIt()
.