Using a class as a member for another class: incomplete type error

Hello,
I'm fairly new to C++ and am having an issue with accessing a member variable that is of another class type.
Here is an example of code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include a.h

class A;

class B
{
public:

//members
std::vector<A*> var;
double answer;

//functions
B(...){    //constructor
...
}

void myfunction() {
     answer = var[0]->arg;
}


};


Where class A has been defined in a.h header file similarly:

1
2
3
4
5
6
7
8
9
class A
{
double arg;

A(...){    //constructor
...
}

};


After initializing/assigning values everything runs fine except for myfunction(), which gives the error: invalid use of incomplete type 'class A'. Does anyone know how to resolve this?
From what you have shown it should compile. Remove the forward reference on line 3.

Eventually: Did you include the header of class B into a.h?
Could this be a compiler problem then? I am using CLion currently.


Eventually: Did you include the header of class B into a.h?


Yes, I forgot to include that in the example code but both A and B classes include each other's headers.

1
2
3
4
5
6
7
8
9
10
11
12
#include b.h

class A
{
double arg;

A(...){        //constuctor
...
}

};
Could this be a compiler problem then?
No
Yes, I forgot to include that in the example code but both A and B classes include each other's headers.
That's the problem: Circular dependancy. It is not possible that the header include each other.

a.h includes b.h include a.h includes ...

Consider using include guards:

https://en.wikipedia.org/wiki/Include_guard

To solve your problem you need to implement myfunction() in (e.g.) b.cpp:
1
2
3
4
5
6
#include "b.h"
#include "a.h"

void B::myfunction() {
     answer = var[0]->arg;
}
Remove the #include "a.h" from the b.h and leave the forward reference where it is.
Ah, I see that now....worse in my actual code as I have four header files all including each other...

I made the changes you suggested and it compiles and runs now.

Thank you very much!!!


Consider using include guards:


My compiler automatically puts them in header files, but I wasn't sure of their use/limitations. Thanks for the article!



Topic archived. No new replies allowed.