Moritz Brösamle
Moritz Brösamle

Reputation: 23

Interdependent classes in C++

Say I want to implement two classes in C++, where each class contains a function returning an instance of the other class:

class A {
  ...
  B fun1() {
    B b;
    return b;
  }
}

class B {
  ...
  A fun2() {
    A a;
    return a;
  }
}

How can I do it? I have tried forward declaring both classes and having prototypes of them in a header file, but every time I run in some type of missing or incomplete definition error. Is there a way to do this? Or do I have to return do I have to return pointers to Objects?

Upvotes: 2

Views: 213

Answers (1)

Artyer
Artyer

Reputation: 40801

You need to forward declare the classes and the member functions that return them (since you can't return an incomplete type)

class B;

class A {
  ...
  B fun1();  // Cannot define since B is not a complete type yet
};

class B {
  ...
  A fun2() {
    // A is complete, so you can declare and define the member function here
    A a;
    return a;
  }
};

// B is now complete, so you can define A::fun1
inline B A::fun1() {
    B b;
    return b;
}

Upvotes: 4

Related Questions