Callum Poole
Callum Poole

Reputation: 3

C++ Returning a child class from within a parent class

So I have two classes like this

#pragma once
#include "B.h"
class A {
public:
    B getB() {}
};

and

#pragma once
#include "A.h"
class B : public A {

};

Error: 'A' base class undefined.

Both need to be declared before the other one so how do I fix this?

If you reorder the code into one file then it looks like this:

#include <iostream>
using namespace std;
class B : public A {

};
class A {
public:
    B getB() {}
};

void main() {
    A a;
    B b = a.getB();
    system("pause");
}

But the problem is still there...

Upvotes: 0

Views: 244

Answers (1)

Johan
Johan

Reputation: 3778

  • Before being used in inheritance, a class should be fully define.
  • Before being used in a value (i.e. member, variable, input parameter, return value), a class should be fully defined.

So here you're stuck. The workaround usually done is to return the class by reference/pointer/shared_ptr:

// Forward declaration
class B;

class A
{
  public:
   B& GetB();
};

class B : public A
{ /* ... */ }

B& A::GetB() { return a_b_from_somewhere; }

But note that you will certainly have to deal with problems of owner ship in that case (i.e. who owns the pointer you return ?)

Upvotes: 1

Related Questions