caring-goat-913
caring-goat-913

Reputation: 4049

C++ Forward Declare Struct In .h File and Define Struct In The .cpp File

I'm looking to forward declare a struct in a header and then hide the implementation in the source file.

mystruct.h

...

struct MyStruct;

...

mystruct.cpp

#include <mystruct.h>
...

struct MyStruct : virtual SomeOtherStruct, virtual AndAnotherStruct {};

...

However when I try to instantiate MyStruct:

main.cpp

#include <mystruct.h>
...

MyStruct structTest;

...

I get the error

"error: aggregate 'MyStruct structTest' has incomplete type and cannot be defined"

How can I declare a structure in the header and then define it later in the source? It's important that MyStruct inherits from other structures. I would like to hide as much implementation detail as possible.

Upvotes: 2

Views: 1567

Answers (1)

Matt Fichman
Matt Fichman

Reputation: 5696

You can use a pointer to the struct. However, you cannot use a value of type MyStruct, because the compiler doesn't know the size/layout of the struct without the struct definition. Since the struct definition is hidden in the .cpp file (and is thus not "visible" when the compiler is processing main.cpp):

MyStruct* structTest;

is allowed in your main.cpp, whereas

 MyStruct structTest;

is not. Additionally, something like:

void foo() {
    MyStruct* test;
    test->someFunc();
}

won't compile if it's put in main.cpp, for the same reason. You should put the struct definition in the header, or use PIMPL, as one of the other commenters noted.

Upvotes: 4

Related Questions