Skip to main content
GameDev.net gamedev.net
🔒 Locked

error: field b' has incomplete type on declaration

Started by OmNomNomNom Nov 21, 2009 at 5:02 AM 4 replies 2.4k views
Original Post
OmNomNomNom
OmNomNomNom
Hi.:) I have a project Im working on and I have this error come up on compile. error: field `b' has incomplete type. After googling it, it seems to be when you try to access a variable that hasnt been initialized (I think that's the word.)But Im getting the problem before I try to do anything with it. Here's the code: A.h

#ifndef A_H
#define A_H

#include "B.h"

class B;

class A
{
    public:
        A();
        virtual ~A();
    protected:
    private:
    B* b; //The error is here, though I guess it would happen to all.
//I also forgot to add that b is a pointer. >_>
};

#endif // A_H


B.h

#ifndef B_H
#define B_H

#include "C.h"
class C;
class B
{
    public:
        B();
        virtual ~B();
    protected:
    private:
    C c;
};

#endif // B_H


C.h

#ifndef C_H
#define C_H

#include "A.h"
class A;
class C
{
    public:
        C();
        virtual ~C();
    protected:
    private:
    A a;
};

#endif // C_H


Thank you!
Brother Bob
Brother Bob
How do you expect this to work? An object of type A contains an object of type B, which contains an object of type C, which contains an object of type A, which contains an object of type B, which contains an object of type C, ad infinitum. There is nothing to stop this recursion of mutual inclusion of types.

The actual compiler error comes from you also including files with circular dependence. A.h includes B.h, which includes C.h, which includes A.h, but at this point, the include guards will stop the recursion and not include anything else, leaving the first class with only a forward declaration, and not a complete definition. And you cannot instantiate objects of a type that isn't fully defined.
OmNomNomNom
OmNomNomNom
I'm sorry, but I forgot to add that b is a pointer. But I do't think this would make a difference.

The original plan of the design was that B contains an object of C, containing a vector of A. The A objects would then have a pointer back to the original B object.

I guess to get around this I could just remove the C object, and just have B with A and A with ptr-to-B?
With the declaration to avoid circular.
Thank you. Sorry if it seems like a noob question.
OmNomNomNom
OmNomNomNom
It now runs fine. Thank you!
And I'm pretty sure I understand why it works as well(which is the important bit).
Thank you two. :D
Brother Bob
Brother Bob
Pointers to objects can be instantiated without a fully defined type, and they don't have to point to an instance of an object. So, using a pointer can break the infinite recursion; both the instantiation and header include recursion. That should work, unless I misunderstood something in your description.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.