I'm trying to make a nested class which is also a subclass of its parent:
struct X { struct Y : public X {}; };
Unfortunately, this doesn't seem to be allowed in C++, as g++ produces the error
error: invalid use of incomplete type 'struct X'
However, my actual code has X
as a templated class:
template<typename T> struct X
{ struct Y : public X {}; };
I get the same message, but this time it's only a warning:
warning: invalid use of incomplete type 'struct X< T >'
My question is: why is the former case illegal, while the templated case just gives a warning? The templated version works exactly as I would expect it to (I can create instances of X<T>::Y
, cast them to X<T>
, and so on), but does the warning mean that I shouldn't use it? What problems can I expect to run into if I ignore the warning?
An inner class is a class that is nested or defined within another class. On the other hand, a subclass is a class that is derived from another class.
A nested class is declared within the scope of another class. The name of a nested class is local to its enclosing class.
A subclass inherits all the members (fields, methods, and nested classes) from its superclass.
To answer the basic question: You get a warning because the template isn't yet instantiated, so it doesn't bother anyone.
The way to fix this, in both cases, would be to define X::Y
at the point in which X
's layout is already known, and thus Y
's layout can be properly deduced. You could do:
struct X { struct Y; }
struct X::Y {};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With