I try to understand the logic behind accessing members of a derived object. I have two pointers: If I change the variable in my derived class via a pointer to the derived class, I notice that I am not able to access the value of the variable via a inheritance type of pointer to the base class.
#include <iostream>
#include <string>
class A
{
public:
int x;
};
class B : public A
{
public:
int y;
};
int main()
{
B* pB = new B;
A* pA = new B;
std::cout<<"Changing x via pB to 11"<<std::endl;
pB->x=11;
std::cout<<"This is x: " << pB->x<<std::endl;
std::cout<<"What about this x: " << pA->x<<std::endl<<std::endl;
std::cout<<"Changing x via pA to 42"<<std::endl;
pA->x=42;
std::cout<<"This is my new x: " << pB->x<<std::endl;
std::cout<<"and what about this x now: " << pA->x;
delete pA;
delete pB;
}
Output:
Changing x via pB to 11
This is x: 11
What about this x: 0Changing x via pA to 42
This is my new x: 11
and what about this x now: 42
I would like to know what has happens and why there are two different values for x. What also bothers me is that when I work, for example, with multiple lists: a master list with pointers to all my objects (say some animal class) and a secondary list--a sub-sample of the master list with pointers to some objects (say class reptile: public animal, public predator)--and it happens that I wish to modify the values of these members through the second list (bool is_currently_in_water), I cannot do this in a straightforward (and to me intuitive) way. I have to keep track of the master list and first find out which animal object is a reptile, in order to make the necessary changes through the master list.
Is polymorphism intended to be like this? This is perhaps a very basic question as I am a beginning to learn C++, and although I know how to overcome the problem my changing my code, I first trying to fully grasp what is going on as the above result was rather surprising.