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.
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());
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