Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a C++ style cast operator change the pointer it casts?

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?

like image 620
mathematician1975 Avatar asked Jul 25 '12 14:07

mathematician1975


1 Answers

The casted pointer can point to another location. In case of multiple inheritance for example. Good read

The original pointer will be preserved

like image 197
Andrew Avatar answered Oct 27 '22 00:10

Andrew