C++ Inheritance – How to Avoid Redundant Code

cinheritance

Say I have a Base class called Car and it has 3 derived classes say Ford, Honda and Audi.

The issue is, all three derived classes have exactly same code but minor difference in calling member functions of their respective engines (these engines have separate class).

For example, Ford class calls code which is exactly same as other two classes but do call something like ford_engine-> start(), ford_engine->clean() etc.

//ly  honda  calls   honda_engine->start()   honda_engine->clean();

//ly  Audi calls audi_engine->start()  audi->clean();

Now here the issue is, it has redundant code in all three places with minute difference. How can I have code at one place, most probably in base class and all derived classes use same code?

Best Answer

The idea is to add a read only protected member variable (i.e. a protected property) engine to your superclass. Then, redefine the accessor in the subclasses to return the proper engine instance. Your code become this->getEngine()->start() and so on.