Search code examples
c++classdeclarationdefinitionforward-declaration

C++ class prototype not working properly?


I'm trying to create a class prototype, however I keep getting the error: 'aClass' uses undefined class 'myClass'

I'm pretty sure I'm making the prototype properly. Using a prototype function works, however class prototype doesn't.

extern class myClass;               // prototypes
extern void myFunction();

int main()                          // main
{
    myClass aClass;
    myFunction();
    return 0;
}

class myClass {                     // this doesn't work
public:
    void doSomething() {
        return;
    }

    myClass() {};
};
void myFunction() {                 // this works
    return;
}

Solution

  • myClass aClass; is a definition, which requires myClass to be a complete type; the size and layout of myClass must be known at that point, at compile-time.

    Any of the following contexts requires class T to be complete:

    • ...
    • definition of an object of type T;
    • ...

    That means the class has to be defined before that.

    Note that forward declaration works for those cases that don't require the type to be complete, e.g. a definition of pointer to the type (like myClass* p;).

    For functions the story is different. A function is odr-used if a function call to it is made, then its definition must exist somewhere. Note that the definition is not required at compile-time, defining it after main() (with declaration before) is fine.

    a function is odr-used if a function call to it is made or its address is taken. If an object or a function is odr-used, its definition must exist somewhere in the program; a violation of that is a link-time error.


    BTW: Using extern in forward declaration of a class is superfluous.