Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is inheritance from a base class with no virtual methods bad practice?

I read an answer some time back to a question regarding dynamic_cast. The dynamic_cast failed to work because the base class had no virtual methods. One of the answers said that deriving from classes with no virtual methods generally means a bad design. Is this correct? Even without taking advantage of polymorphism, I still can't see the wrongness in doing this.

like image 456
Luchian Grigore Avatar asked Aug 09 '11 14:08

Luchian Grigore


1 Answers

It depends what we're talking about:

  • for Traits classes (no data) it's fine (std::unary_function comes to mind)
  • for private inheritance (used instead of composition to benefit from Empty Base Optimization) it's fine too

The problem comes when you starts treating such a Derived object polymorphically wrt this Base class. If you ever attain such a position, then it's definite code smell.

Note: Even when noted as fine above, you are still providing the ability to use the class polymorphically, and you thus expose yourself to subtle bugs.

like image 155
Matthieu M. Avatar answered Sep 29 '22 14:09

Matthieu M.