Suppose I have the following hierarchy:
class A
{
public:
A()
private:
int aa;
}
class B: public A
{
public:
B()
private:
int bb;
}
class D: public B
{
public:
D()
private:
int dd;
}
When I type in the following code in my main:
D dobj;
std::cout<<"Address of D object: "<<&dobj<<std::endl;
A aobj = static_cast<A>(dobj);
A* aptr = static_cast<A*>(&dobj);
std::cout<<"Address of D object: "<<&dobj<<std::endl;
std::cout<<"Address of aptr object: "<<&aptr<<std::endl;
std::cout<<"Address of A object: "<<&aobj<<std::endl;
The output of which is:
Address of dobj object: 0012FF0C
Address of dobj object: 0012FF0C
Address of aptr object: 0012FF18
Address of aobj object: 0012FF14
Why is the address of aptr and aobj different ?? Aren’t they supposed to be the same ??
And why is the address of dobj and aptr different ?? Aren’t they supposed to be same as well ??
I am compiling on windows using VC++.
Thanks,
De Costo.
First, you are printing out the wrong pointer:
&aptris “the address ofaptr,” not “the address of the object to whichaptrpoints.” You need to print justaptrto print “the address of the object to whichaptrpoints,” which is presumably what you really want to do.aptris a pointer to theApart ofdobj.aobjis a copy of theApart ofdobj.aptrand&aobjare different because they are the addresses of different objects.