Implicit conversion vs static_cast on raise

Say I have three classes: A (mother, abstract) and B and C, children A.

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

The question arises: what is the preferred style when performing casting / transformation?

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 security, which one is better? I understand that static_cast is easier to look for, but in this case an implicit conversion should be enough.

+5
source share
2 answers

You do not need static_cast base class, static_cast - go in the other direction. So it's ok

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

The time you need to do static_cast is to do something different from A* to the derived class B*

 B* some_obj = static_cast<B*>(myList.front()); 
+7
source

I would like to dwell on the answer provided already with a very general solution.

Never explicitly use what the compiler is already implicitly using for you.

We can even generalize this further:

People make mistakes. Never explicitly do what the compiler already does for you.

... although this may be a little more controversial in some very obscure exceptional cases. The previous sentence should always be true.

The fair use of excess simply violates the DRY principle and, more importantly, causes human error and confusion in the future.

Therefore, avoid explicitly throwing anything that does not require it. Explicit spells are weapons: too often flaunting them too often, and someone may suffer.

0
source

Source: https://habr.com/ru/post/1234694/


All Articles