Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting pointer-to base class into a pointer-to derived class

Tags:

c++

casting

I have read a bit about casting in C++. Coming from a C background, using normal (type) casting is common for things like void * but for C++, there are dynamic_cast, reinterpret_cast, static_cast, etc.

The problem/issue/question is about which of the above casts should be used when a conversion between a base pointer and a derived pointer.

Our data storage stores a pointer to a base class (B). The functions allocate the derived pointers (D).

The code example is as follows:

class B
{ int _some_data; }
class D : public B
{ int _some_more_data; }

The code then looks something like:

D *obj = new D;
obj->_some_data = 1;
obj->_some_more_data = 2;
<store obj>

Then later when we access the data:

B *objB = <get out data>
if (objB->_some_data == 1)
{ D *objD = (D *) objB; <do some processing> }

Now the cast I am concerned about is D *objD = (D *) objB.

Which cast should we be using?

Thanks.

like image 694
user626201 Avatar asked Dec 27 '22 05:12

user626201


1 Answers

In this case, no cast is truly safe.

The safest would be dynamic_cast, but your objects aren't polymorphic so it doesn't apply here. But you should consider at least having a virtual destructor, as I can see you plan on extending the classes.

static_cast is not safe, as pointed out by this msdn page:

class B {};

class D : public B {};

void f(B* pb, D* pd) {
   D* pd2 = static_cast<D*>(pb);   // not safe, pb may
                                   // point to just B

   B* pb2 = static_cast<B*>(pd);   // safe conversion
}

reinterpret_cast also has no checks, so don't rely on it.

Also, casting to a pointer of a derived class is at least a code smell, if you need to do this it's 99% sure you have a flawed design.

like image 169
Luchian Grigore Avatar answered Dec 29 '22 20:12

Luchian Grigore