Avoid Redundant code in derived classes.

Hi Folks,

ISSUE: How to avoid redundant code in c++ ?

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

now the issue is all 3 derived classes have exactly same code but minor difference in calling member functions of their r respective engines( these engines have separate class) . example ford class calls code which is exactly same as other 2 classes but do call something like ford_engine-> start() ford_engine->clean() bla bla bla .

//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 3 places with minute difference. I am requesting you guys to suggest something so that I can have code at one place most probably in Base class and all derive classes uses same code.

Thanks in advance
You can define the common code in the base class virtual member functions, and have the derived classes override the member functions to do the different things and then call the base class version. Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
struct Engine
{
    virtual void start()
    {
        //common code
    }
};

struct FordEngine
: virtual Engine
{
    virtual void start() override
    {
        //code
        Engine::start(); //call common code
        //code
    }
};


(Who reported your post?)
Topic archived. No new replies allowed.