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)
A static nested class can inherit: an ordinary class. a static nested class that is declared in an outer class or its ancestors.
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 .
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.
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.
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 {};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With