Click here to Skip to main content
15,889,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have got myself into a strange issue now. Ill write a really simplified version of the same.
C++
class Base
{
public:
virtual int func1()=0;
virtual int func2()=0;
protected:
int n;
};

class der1: public Base
{
//implements the virtual functions of the base and uses the protected data members of the base.
};

class der2: public Base
{
//implements the virtual functions of the base and uses the protected data members of the base.
}


Now the problem.... both der1 and der2 implements the virtual functions of base pretty much the same way. But some other classes (der3, der4) has their own implementations. But still need to inherit from base.
How do i refactor the code to remove the code duplication in an oop manner?

What I have tried:

I don't want a function to have the common code and then from the der1 and der2 to call it. That won't be possible unless I send all the protected variables of base to it as an argument. Didn't quite like the approach.
So, looking for a OOP approach to handle this problem,
Posted
Updated 20-Oct-18 23:25pm
Comments
Rick York 21-Oct-18 18:31pm    
"That won't be possible unless I send all the protected variables of base to it as an argument." This is not true. If you do as Mr. Griff suggests, Intermediate provides a default implementation and nothing else has to implement func1 and func2 unless you want differing behavior. Also, Intermediate will have access to all public and protected members and methods of Base.

1 solution

Derive a third class from Base which handles the "common" implementation:
C++
class Intermediate: public Base
   {
   ...
   }
Then derive your classes from that:
class der1: public Intermediate
   { 
   ...
   };

class der2: public Intermediate
   {
   ...
   }
 
Share this answer
 
Comments
_PitrakSarkar_ 21-Oct-18 5:33am    
the problem with this solution I feel is, now intermediate has to implement the pure virtual functions of Base and again, der1 and der2 also have to implement the same. Is there a better way?
OriginalGriff 21-Oct-18 5:39am    
No, Intermediate provides concrete implementations, which are inherited by der1 and der2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900