Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit conversion vs. static_cast when upcasting

Let's say I have three classes: A (the mother, abstract), and B and C, the children of A.

So B and C inherit from A (public inheritance). I have a list of pointers to A, which I populate with pointers of B or C.

The question is: which is the preferred style when doing the casting/conversion?

class A {};
class B : public A {};
class C : public A {};

B* objB = new B();
C* objC = new C();

std::list<A*> myList;
// Option A: static cast conversion
myList.push_back(static_cast<A*> (objB));
myList.push_back(static_cast<A*> (objC));

// Option B: implicit conversion
myList.push_back(objB);
myList.push_back(objC);

// Option C: C-style conversion (I understand that this is evil and must be avoided)
myList.push_back((A*) objB);
myList.push_back((A*) objC);

So, in terms of clarity (code style) and in terms of safety, which one is better? I understand that static_cast is easier to search for, but on this case, an implicit conversion should be enough.

like image 915
fern17 Avatar asked Oct 28 '15 12:10

fern17


1 Answers

You don't have to static_cast to the base class, the static_cast is to go the other direction. So this is fine

myList.push_back(objB);
myList.push_back(objC);

The time you'd have to static_cast is to do something casting an A* to a derived class B*

B* some_obj = static_cast<B*>(myList.front());
like image 145
Cory Kramer Avatar answered Oct 23 '22 05:10

Cory Kramer