Tony the Pony
Tony the Pony

Reputation: 41357

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)

Upvotes: 27

Views: 8961

Answers (5)

Richard Wolf
Richard Wolf

Reputation: 4109

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

Upvotes: 55

pngaz
pngaz

Reputation: 375

It's always worth considering the ATL method of "Upside-Down Inheritance". It makes my head hurt every time I need to do this, but the efficiency of the object-code you get is unbeatable. Somewhere I clipped the article by Jim Beveridge which was the best explanation I ever saw, but this is hard to find today, I just see a reference to it.

"Mar 25, 2004 ... An excellent article from Jim Beveridge: ATL and Upside-Down Inheritance.."

Upvotes: 1

Tadeusz Kopec for Ukraine
Tadeusz Kopec for Ukraine

Reputation: 12403

The class type is considered incomplete until the end of its definition is reached. You cannot inherit from incomplete class so you cannot inherit from enclosing class.

EDIT: Correction
As Richard Wolf corrected me: It is possible to inherit from enclosing class if you delay the definition of the nested classes. See his answer for details.

Upvotes: 15

Corwin Joy
Corwin Joy

Reputation: 643

I'm not clear what you are trying to achieve here but you may be able to get it via namespaces.

namespace creatures
{

class Animal
{
};

class Bear : public Animal
{
};

class Giraffe : public Animal
{
};


}

This declares Bear and Giraffe as types of animals but puts the whole thing in a namespace if you are looking for the base class to not pollute the global namespace.

Upvotes: 1

Luc Touraille
Luc Touraille

Reputation: 82041

Doesn't really answer the question, but I think you're misusing nested class, maybe you should have a look at namespaces (by the way, the answer is "it's not possible, because Animal is an incomplete type").

Upvotes: 1

Related Questions