I am quite happy using the C++ style casting operators within my code but I cannot say that I truly understand what goes on behind the scenes. I am basically wondering what actually is happening to the pointer during the following short process:
class A {};
class B : public A {};
class C : public B {};
A* pC = new C();
B* b = static_cast<B*>(pC); // Is the value of pC changed by the cast?
C* c = static_cast<B*>(pC); // Is the value of pC changed by the cast?
B* b2 = static_cast<B*>(c) // Is the value of c now equal to the value of b2?
I realise that the object pointed to by pC
is always of type C
but after the first cast is made, I assume that the address stored in b
is no longer equal to that of pC
. But if the cast changes the value of pC
my assumption is wrong. In a nutshell, can the cast operators actually change the address of the pointer they cast? This may seem a pretty facile question, but in my mind the picture is just not clear of how objects with an inheritance hierarchy are stored within memory and how the pointers get manipulated via the casts.
In my head the value of pC
remains unchanged no matter how many casts are performed on it but is this thinking correct?
The casted pointer can point to another location. In case of multiple inheritance for example. Good read
The original pointer will be preserved
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With