Klapek
Klapek

Reputation: 31

C++ forward class declaration

I have 2 classes A and B, simplyfing:

class A {
public:
    void someMethod() {
        //////
        B* b = new B(); //Error
    }
};

class B:A{
    ////
};

What I have to do to use child class object in parent class?

Upvotes: 0

Views: 141

Answers (2)

vsoftco
vsoftco

Reputation: 56547

You need to define the member function after the class B is fully defined, like:

class A {
public:
    void someMethod();
};

class B: A {
    ////
};
void A::someMethod()
{
    //////
    B* b = new B(); //Error
}

int main()
{
    A a;
    a.someMethod();
}

If you only use a forward declaration but the definition of the member function is before class B is fully defined, it won't work, as new B requires B to be fully defined.

Upvotes: 2

R Sahu
R Sahu

Reputation: 206577

You can use

    B* b = new B();

only if the definition of class B is fully visible.

Move the implementation of the function after B is defined.

class A {
  public:
    // Declare only
    void someMethod();
};

class B : A {
    ////
};

void A::someMethod() {
    B* b = new B();
}

Upvotes: 1

Related Questions