Sign in to follow this  
M-374 LX

"invalid use of incomplete type" and "forward declaration"

Recommended Posts

These are the files: a.h:
#ifndef _A_
#define _A_

#include "b.h"

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

#endif
b.h:
#ifndef _B_
#define _B_

class A;

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

#endif
b.cpp:
#include "b.h"

void B::test()
{
	parent->test();
}
main.cpp:
#include <stdio.h>

#include "a.h"

void A::test()
{
	printf("Test.\n");
}

int main()
{
	return 0;
}
I try to compile, but I get errors:
g++ test.cpp b.cpp
b.cpp: In member function ‘void B::test()’:
b.cpp:5: error: invalid use of incomplete type ‘struct A’
b.h:4: error: forward declaration of ‘struct A’
Notice that I do not get any errors if I comment a part of b.cpp:
void B::test()
{
	//parent->test();
}
What causes the errors?

Share this post


Link to post
Share on other sites
When the compiler attempts to compile b.cpp, b.cpp includes b.h, which provides the forward declaration 'class A;', but not the definition of the class (because that is in a.h, not in b.h). So the compiler knows that 'A' names a class, but it doesn't know that it has a member function called 'test', so it can't use that.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this