Search code examples
c++classforward-declarationmember-functions

How can I use a member function of a forward declared class?


I have 2 classes A and B and the 4 following files:

A.h

#ifndef A_H
#define A_H

#include "B.h"
class A {
public:
    A();
    int functionA();
    B objectB;
};

#endif //A_H

B.h

#ifndef B_H
#define B_H

class A;
class B {
public:
    B();
    int functionB();
    A * objectA;
};

#endif //B_H

A.cpp

#include "A.h"
A::A(){}
int A::functionA() {
    return 11;
}

B.cpp

#include "B.h"
B::B(){}
int B::functionB() {
    return objectA->functionA();
}

Now I compile using the line: g++ A.cpp B.cpp -Wall -Wextra -O2 -march=native -std=gnu++1z

I get this error:

B.cpp: In member function 'int B::functionB()':
B.cpp:4:19: error: invalid use of incomplete type 'class A'
     return objectA->functionA();
                   ^
In file included from B.cpp:1:0:
B.h:1:7: note: forward declaration of 'class A'
 class A;
       ^

How can I use a member class of the function forward declared here?


Solution

  • Look at what is included when compiling B.cpp, you have a forward declaration of class A but not the real definition. So in B.cpp on line 4, functionA is unknown to the compiler therefore your type is incomplete.

    You should include A.h in B.cpp.