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

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

hijras

#ifndef A_H
#define A_H

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

#endif //A_H

Bh

#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 will compile 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 the member class of the forward function declared here?

+4
source share
3 answers

See what is included when compiling B.cpp, you have a forward declaration of the class A, but not a real definition. Therefore, B.cppin line 4, functionAit is unknown to the compiler, so your type is incomplete.

You must include A.hin B.cpp.

+3
source

A.cpp A.h B.h
B.cpp B.h , A.h.

, :

  • ( , , )
  • "", , , " ". , , .

( !) .cpp, . , foo.cpp bar, bar bar.h, foo.cpp bar.h. , , .

+2

Using class members with only direct declaration is not possible.

If your code uses a member function, the class must be fully declared, because the compiler must check if a member function with this name exists.

0
source

Source: https://habr.com/ru/post/1686895/


All Articles