3

Suppose I have an application which has multiple classes (inheritance used) Now one day, I have to add new specification to my application and that would require me to use multiple inheritance.

for example this code:

class A{};
class B : public A{};
class C : public A{};

now my new functionality would require me to do this:

class D{} : public B,public C{};

But this will lead to diamond problem.

So my question is, how to overcome this problem : 1) As a best practice, I will use virtual inheritance for all classes, assuming that I may need to use multiple inheritance in future ? or 2) I will simply change my code, make my base classes virtual whenever required ?

curiousguy
  • 8,038
  • 2
  • 40
  • 58
Neeraj gupta
  • 171
  • 1
  • 2
  • 9

1 Answers1

1

One good way to overcome this problem is to decouple the behaviors you are trying to get from your classes into components.

Right now you have a situation like this

class A {}
class B : public A {some behavior X}
class C : public A {some behavior Y}
class D : public ? {I need X and Y plus some behavior Z}

One (potentially bad) way to solve this is to just extend from B or C and then just copy the behavior you need from the other, but this is duplicating code.

What you may be able to do is to make your behaviors into components:

class Behavior {void behave() = 0}

This would be a pure virtual class that we could call an interface. You could then do:

class BehaviorX : public Behavior {void behave(){behavior x}}
class BehaviorY : public Behavior {void behave(){behavior y}}
class BehaviorZ : public Behavior {void behave(){behavior z}}

This would allow to you make new classes that extend from A but you can pick and choose which behaviors they have:

class D : public A {BehaviorX, BehaviorY, BehaviorZ, ...}

If you really wanted to take component modeling to the next level you could get rid of making children classes all together and just use class A as a component bag that could use any number of behaviors you can dream up, and then you could just make new "classes" wherever you wanted that only have the behaviors you want them to:

A likeB = new A(BehaviorX);
A likeC = new A(BehaviorY);
A likeD = new A(BehaviorX, BehaviorY, BehaviorZ);
A likeE = new A(BehaviorY, BehaviorZ, Behavior?);
ekcell
  • 105
  • 2
  • 11