R
responsible
Hi,
Please have a look at this very small piece of code...
class Base1{
public:
Base1():x(5){}
int x;
};
class Base2{
public:
Base2():y(7){}
int y;
};
class Base3{
public:
Base3():z(9){}
int z;
};
class Derived
ublic Base1, public Base2,public Base3{
public:
Derived():w(12){}
int w;
};
int main(void)
{
Derived* p_d = new Derived;
Base1* p_b1 = dynamic_cast<Base1*> (p_d);
Base2* p_b2 = dynamic_cast<Base2*> (p_d);
Base3* p_b3 = dynamic_cast<Base3*> (p_d);
Derived* p_d2 = static_cast<Derived*> (p_b2);
delete p_d;
return 0;
}
The code just has 3 base classes, and one class that derives from all
three of them.
Now, when I cast from Derived to any of the bases, I understand that
the pointer value may change because otherwise the new pointer will
not be able to figure out where the virtual table entry is, right?
My question, however, is, how does performing the static cast from
Base2* to Derived* "know" that it should change the address back? The
code surprisingly works fine (when you cast a Base2* to a Derived* it
automatically decrements the pointer by 4 bytes.)
Is this behavior part of the C++ language? I was curious about how it
works inside.
Thank you very much in advance
Please have a look at this very small piece of code...
class Base1{
public:
Base1():x(5){}
int x;
};
class Base2{
public:
Base2():y(7){}
int y;
};
class Base3{
public:
Base3():z(9){}
int z;
};
class Derived
public:
Derived():w(12){}
int w;
};
int main(void)
{
Derived* p_d = new Derived;
Base1* p_b1 = dynamic_cast<Base1*> (p_d);
Base2* p_b2 = dynamic_cast<Base2*> (p_d);
Base3* p_b3 = dynamic_cast<Base3*> (p_d);
Derived* p_d2 = static_cast<Derived*> (p_b2);
delete p_d;
return 0;
}
The code just has 3 base classes, and one class that derives from all
three of them.
Now, when I cast from Derived to any of the bases, I understand that
the pointer value may change because otherwise the new pointer will
not be able to figure out where the virtual table entry is, right?
My question, however, is, how does performing the static cast from
Base2* to Derived* "know" that it should change the address back? The
code surprisingly works fine (when you cast a Base2* to a Derived* it
automatically decrements the pointer by 4 bytes.)
Is this behavior part of the C++ language? I was curious about how it
works inside.
Thank you very much in advance