c++inheritancenested-class

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


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)


Solution

  • 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 {};