Search code examples
c++structforward-declaration

forward declaration of struct doesn't work - can't figure out why


I'm trying to make a forward declaration of a struct. But it doen't work.

typedef struct BEAST_Coord2D BEAST_Coord2D;
typedef struct BEAST_Vertex BEAST_Vertex;

struct BEAST_Vertex {
    BEAST_Coord2D absolut;
    BEAST_Coord2D relativ;
};

struct BEAST_Coord2D {
    float x;
    float y;
};

Visual Studio 2017 says: "error C2079: 'BEAST_Vertex::absolut' uses undefined struct 'BEAST_Coord2D' error C2079: 'BEAST_Vertex::relativ' uses undefined struct 'BEAST_Coord2D'

I have made a simple header-file for all of my structs. What's wrong here?

Best starcow


Solution

  • Forward declaring a class allows you to do some things with it, but not all things.

    Declaring an instance of that class is not one of those things. More information is required to do this than just its name; you'll need to provide its actual definition first.

    If BEAST_Vertex only declared pointers to BEAST_Coord2D then you'd be okay (what a pointer is is always known to the compiler).

    Fortunately, in this contrived example at least, the fix is simple: swap the class definitions and drop the forward declarations:

    struct BEAST_Coord2D
    {
        float x;
        float y;
    };
    
    struct BEAST_Vertex
    {
        BEAST_Coord2D absolut;
        BEAST_Coord2D relativ;
    };
    

    By the way, you're using C idioms here which are unnecessary. A C++ forward declaration just looks like this:

    struct BEAST_Coord2D;
    struct BEAST_Vertex;
    

    What you've done instead is to mix a forward declaration with a typedef (a C idiom used to eliminate the need to keep writing struct everywhere afterwards), which is perfectly valid but not necessary in C++ (which does not require you to keep writing struct in the first place).