Search code examples
c++inheritancevirtual

Circular Inheritance in c++


I have three classes and I want to use each of them inside another likeso:

class Object
{
public:
    Object();
    ~Object();


protected:

   int x;
   int y;
private:
  Line l;
  Circle c;
}; 

class Line : public Object
{
public:
    Line ()
        {
           x = x+y;
         }
    ~Line ();


private:
}; 

class Circle : public Object
{
public:
    Circle()
        {
           x = x/y;
         }
    ~Circle();


private:
}; 

So the problem here is that I get an error on compilation which says base undefined, I have tried to use #define and #ifdefine, but it doesn't work.

Ideally, what I want to do is to have one object in main to call and all other variables to be used will be set there and at the same time this object could be different such that it could be a Line or Circle.


Solution

  • My guess is that you want any object to be either a primitive graphical object, like a line or a circle, or a compound object, ie. an object containing several others.

    Your are actually almost there: what you should do is:

    • remove the Object subclasses instances from Object (see other answers for the reason behind this being a design mistake),

    • create a fourth class inheriting of Object:

      class Compound : public Object {
        public:
          Compound(){
          }
        private:
         Line line;
         Circle circle;
      };
      

    Now if you want to manipulate in a generic way a list of objects, it's easy. All you need is to define the ad-hoc virtual methods on Object, and override them in the subclasses (for instance a draw method).

    See this tutorial on polymorphism for more explanations on the concept.