Forward declare a subclass that inherits from a class in different namespace
I don't understand why this fails to compile:
#include <SomeType.h> // has a namespace called SomeNamespace
class MyApplication;
int main(...)
{
...
MyApplication application;
...
}
class MyApplication : public SomeNamespace::SomeType {
...
};
As it stands I'm getti开发者_如何学运维ng this error from g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3
../fix-protocol/main.cpp:44: error: aggregate ‘MyApplication application’ has incomplete type and cannot be defined
In main
you're instantiating an object of type MyApplication
, which is still an incomplete type; you can't do that, since the compiler doesn't know anything about it yet (it would need to know e.g. how big is it, if it has any constructor, ...).
To solve your problem, you have to define MyApplication
before instantiating objects of that type. Usually you place the class definition in a separate header with its name, that will be #include
d in any file that needs it.
Forward declarations, instead, in general are used to break cyclic dependencies and other scenarios of that kind; all they say is "there's a class named like that", but they create an incomplete type, so they can be used only to declare variables of their type, not to define them.
You need to place the definition of MyApplication
before any instantiations. In the above code, the compiler doesn't know how much stack space to allocate for the application
variable, because it hasn't seen the definition of MyApplication
yet.
class must be fully defined before an object is instantiated. MyApplication application;
, you are trying to instantiate an object application
but the compiler isn't aware of what constitutes of MyApplication
since it is forward-declared. So, place the definition before main()
and remove the forward declaration.
class MyApplication : public SomeNamespace::SomeType {
...
};
int main()
{
MyApplication application;
}
The problem is that C++'s compiler is one-pass, meaning that at any point in the program it needs to be able to operate without looking at the rest of the file. In your case, the problem is that in your main
function, when you write
MyApplication application;
The compiler has so far only seen a forward declaration for the class (the class MyApplication;
line up above). Although you do provide a definition for the class later on, the compiler hasn't seen it yet, and so it thinks you're trying to instantiate a class you have not yet defined.
To fix this, either move the definition of MyApplication
up in the file above main
, or move main
later in the file after the definition of MyApplication
.
By the way, this has nothing to do with inheritance - it's just an issue of where the class is defined.
I think your missing the point of forward declaration of types. This answer explains it very well, and using a not-yet-declared-only-forward-declared type as base class is not possible.
精彩评论