Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested subclasses in C++

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?

like image 472
gilgamec Avatar asked Jan 28 '16 14:01

gilgamec


People also ask

Is nested class a subclass?

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.

What is nested class in C?

A nested class is declared within the scope of another class. The name of a nested class is local to its enclosing class.

Do subclasses inherit nested classes?

A subclass inherits all the members (fields, methods, and nested classes) from its superclass.


1 Answers

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 {};
like image 199
Yam Marcovic Avatar answered Oct 26 '22 06:10

Yam Marcovic