Can a nested C++ class inherit its enclosing class?

Tony the Pony picture Tony the Pony · Sep 28, 2009 · Viewed 7.1k times · Source

I’m trying to do the following:

class Animal
{
    class Bear : public Animal
    {
        // …
    };

    class Giraffe : public Animal
    {
        // …
    };
};

… but my compiler appears to choke on this. Is this legal C++, and if not, is there a better way to accomplish the same thing? Essentially, I want to create a cleaner class naming scheme. (I don’t want to derive Animal and the inner classes from a common base class)

Answer

Richard Wolf picture Richard Wolf · Sep 28, 2009

You can do what you want, but you have to delay the definition of the nested classes.

class Animal
{
   class Bear;
   class Giraffe;
};

class Animal::Bear : public Animal {};

class Animal::Giraffe : public Animal {};