jecyhw
jecyhw

Reputation: 141

c++ two class reference each other Error: expected type-specifier before 'ClassName'

i write two class in a header file, like below, and the two class reference each other, and i add class B before use in A class, but it has a error.

#ifndef TEST_H
#define TEST_H
class B;
class A {
public:
    B *b;
    void test() {
        b = new B();
    }
};

class B {
public:
    A *a;
    void test() {
        a = new A();
    }
};

#endif // TEST_H

error message image

how to solve it? Thank you.

Upvotes: 3

Views: 81

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118445

b = new B();

At this point, the forward declaration is no longer sufficient. The definition of class B must be known in order to instantiate an instance of the class.

Just need to delay the definitions of both test methods until both classes are defined:

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

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

inline void A::test() {
    b = new B();
}

inline void B::test() {
    a = new A();
}

Well, technically, it's not necessary to relocate the definitions of both class's test() methods, but it looks neater this way.

Upvotes: 2

Related Questions