0

I have an unsolved problem that I'd like to ask about circular dependencies in c++. Assume I have two classes that inherit from another class. In all of those three classes definitions, I've a member functions that initialize two objects from the other two, as follows.

class A{
  public:
  ...
  A* test(){
     A* first=new B();       
     A* second= new C();
   }
 };

 class B:public A{
  public:
  ...
  A* test(){
     A* first=new A();       
     A* second= new C();
   }
 };

 class C:public A{
  public:
  ...
  A* test(){
     A* first=new A();       
     A* second= new B();
   }
 };

The compiler error that I get is: "error C2027: use of undefined type 'B'" and "error C2027: use of undefined type 'C'".

1 Answers1

1

Do forward declarations before class A, like this:

class B;
class C;

class A{
//...

Don't use inline definitions of test() methods, define them out of the classes:

class A{
public:
    A* test();
};

class B:public A{
public:
    A* test();
};

class C:public A{
public:
    A* test(){
        A* first=new A();
        A* second= new B();

        return first; //Add return
    }
};

Somewhere in main.cpp methods definitions:

A* A::test()
{
    A* first=new B();
    A* second= new C();

    return first; //Add return
}

A* B::test()
{
    A* first=new A();
    A* second= new C();
    return first; //Add return
}

Also your methods should return pointer, for return first;

Alexey Usachov
  • 1,364
  • 2
  • 8
  • 15