Mahathi Vempati
Mahathi Vempati

Reputation: 1398

Inherit same class twice in C++ (on purpose)

I have a Circle class and a Rectangle class. I now want to make a class FunnyObject, each made of one circle and two rectangles.

If I do this:

class FunnyObject:public Circle, public Rectangle, public Rectangle{
//How do I refer to each of the Rectangle classes?

}

How do I refer to the functions and variables in both the Rectangle classes, since there is ambiguity?

Also, generally the constructor is:

FunnyObject::FunnyObject:Circle(arguments), Rectangle(arguments){
//....
}

How will the constructor look in my case?

Upvotes: 2

Views: 1328

Answers (4)

Baltasarq
Baltasarq

Reputation: 12212

As you said:

I have a Circle class and a Rectangle class. I now want to make a class FunnyObject, each made of one circle and two rectangles.

"... each made of one circle and two rectangles." The solution is in the wording of your own question. As @scoohe01 said, one trick is to choose between FunnyObject is a Circle and two Rectangles, or FunnyObject is composed by a Circle and two Rectangles. In your case, and following the wording you chose, your design should correspond to the latter choice.

Another trick is that you cannot inherit more than once. In your example, you would like to inherit twice from Rectangle. Suppose there is a getSide1() method. How would you refer to it? getSide1'1() and getSide1'2()... there is just no way.

It is also confusing. If you inherit from a Circle and a Rectangle, you will end up with a mixing (thus its name) with methods like getRadius(), getSide1() and getSide2(). It would be seem to have both a radius and sides, which makes no sense.

Finally, there is the subclassing rule or Liskov's substitution principle. Can the inheriting class (FunnyObject?) be used in all situations in which a Circle or a Rectangle is used? Not at all. Well, at least in a meaningful way.

Hope this helps.

Upvotes: 2

Haroon
Haroon

Reputation: 591

You don't need inheritance in this case, use composition:

class FunnyObject
{
    Circle myCircle;
    Rectangle myRectangle1;
    Rectangle myRectangle2;
}

Upvotes: 5

scohe001
scohe001

Reputation: 15446

An easy trick to help with inheritance is to think about "is a" vs. "has a".

If you have an "is a" relationship, you use inheritance. If you have a "has a" relationship, you make a new data member.

Is FunnyObject a Rectangle and a Circle? If so, inherit.

Does FunnyObject have two Rectangles and Circle? If so, make member variables.

Upvotes: 8

R Sahu
R Sahu

Reputation: 206607

I have a Circle class and a Rectangle class. I now want to make a class FunnyObject, each made of one circle and two rectangles.

Use object composition rather than inheritance.

class FunnyObject
{
    Circle circle;
    Rectangle rectangle1;
    Rectangle rectangle2;
}

Upvotes: 8

Related Questions