Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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)

like image 668
Tony the Pony Avatar asked Sep 28 '09 08:09

Tony the Pony


People also ask

Can nested classes be inherited?

A static nested class can inherit: an ordinary class. a static nested class that is declared in an outer class or its ancestors.

Are nested classes inherited C++?

A nested class may inherit from private members of its enclosing class. The following example demonstrates this: class A { private: class B { }; B *z; class C : private B { private: B y; // A::B y2; C *x; // A::C *x2; }; }; The nested class A::C inherits from A::B .

Can an inner class method have access to the fields of the enclosing class?

Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.

Is nested class a derived class?

If a class is nested in the public section of a class, it is visible outside the surrounding class. If it is nested in the protected section it is visible in derived classes, if it is nested in the private section, it is only visible for the members of the outer class.


1 Answers

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 {}; 
like image 131
Richard Wolf Avatar answered Sep 22 '22 03:09

Richard Wolf