c++ - How can I avoid code repetition without losing the interfaces?

Below is current code design (sample). How can I avoid repetition of the code for "methodParent()" (in implementation of both child classes) without losing interface classes?

//Interfaces

//=======================================================

class InterfaceParent() //Interface class

{

public:

virtual void methodParent() = 0;

};

class InterfaceChild1() : public InterfaceParent //Interface class

{

public:

virtual void methodParent() = 0;

virtual void methodChild1() = 0;

};

class InterfaceChild2() : public InterfaceParent //Interface class

{

public:

virtual void methodParent() = 0;

virtual void methodChild2() = 0;

};

// Concrete Classes

//=========================================================

class Child1() : public InterfaceChild1 // Concrete Class

{

public:

void methodParent() { cout << "PARENT_METHOD"; }

void methodChild1() { cout << "CHILD_1_METHOD"; }

};

class Child2() : public InterfaceChild2 // Concrete Class

{

public:

void methodParent() { cout << "PARENT_METHOD"; }

void methodChild2() { cout << "CHILD_2_METHOD"; }

};

Thanks for the help in advance !

Santosh

网友答案:

If you see "methodParent()", I need to implement it in all the child
classes and is lots of repetition of the code (as well as maintenance
hurdle) for me.

Then implement an Abstract class instead of your interface. Basically it's an interface (containing pure virtual methods that will need to be implemented in childrens) but also containing some "non-pure" (already implemented) virtual methods, that can be overriden later if needed.

In general an abstract class is used to define an implementation and
is intended to be inherited from by concrete classes.
More here