Is there a way to have two (or more) classes which each can create an object of the other in c++?

62 Views Asked by At

So I have two classes inherites from a base class, and I want each of them to have members that call the constructor for the other. Something like;

class BaseClass {

   protected:
      BaseClass* a;

   public:
      virtual void Create() {}
}

class Class1 : public BaseClass {

   public:
      void Create() {
         a = new Class2;
      }
}

class Class2 : public BaseClass {

   public:
      void Create() {
         a = new Class1;
      }
}

Of course it gets unhappy if you try that because whichever one you put first is trying to create an object with an undeclared type.

I have tried forward declaration. Of course it didn't work because it would have to know the structure of the class but I tried it anyway.

I don't really know what else to try or if it's actually possible. It doesn't seem like a situation that would cause any logic errors or infinitely large objects or anything.

1

There are 1 best solutions below

1
Sam Varshavchik On

I have tried forward declaration. Of course it didn't work

Not sure what you tried, but the following forward declarations compile just fine:

class BaseClass {

   protected:
      BaseClass* a;

   public:
      virtual void Create() {}
};

class Class1 : public BaseClass {

public:
    void Create();
};

class Class2 : public BaseClass {

public:
    void Create();
};

void Class1::Create() {
    a = new Class2;
}

void Class2::Create() {
    a = new Class1;
}

The code you showed lacked semicolons in a few places, so it's possible that it wasn't the real code you were trying to compile. It's possible that your real code has a different issue, but the shown code, after fixing the compilation errors, can be made to compile as shown above.