Search code examples
c++oopinheritancemultiple-inheritance

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?


Solution

  • 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.