When do I need to use a nested class in C++? What does a nested class provide that cannot be provided by having two classes?
class A
{
class B
{
};
};
and not:
class A
{
};
class B
{
};
When do I need to use a nested class in C++? What does a nested class provide that cannot be provided by having two classes?
class A
{
class B
{
};
};
and not:
class A
{
};
class B
{
};
I think you're getting a little confused.
In your first example, class B
is nested within class A
. This is a good idea when class B
is really quite specific to class A
, and might pollute the namespace. For example:
class Tree
{
class Node
{
};
};
Depending on what other 3rd-party libraries you are using, Node
might well be already defined. By nesting Node
in Tree
, we are explicitly saying which kind of Node
we're talking about.
In you 2nd example, if there are other Node
classes in the namespaces, there could be conflicts.
A cat is an animal. We can define Cat
and Animal
classes as follow:
class Animal {};
class Cat {};
But we have defined them without any relationship to each other, So a Cat
is not an Animal
. We can define an IS-A relationship between them (Inheritance):
class Animal {};
class Cat : public Animal {};
Then we can do this:
Animal* animal = new Cat();
Now Cat
is a subclass of Animal
(IS-A relationship). by this way; we can implement dynamic polymorphism which Cat
acts like Animal
but has its own style/behavior.
But we could define them as follow (Nested Class):
class Cat
{
class Animal {};
};
It is useless and wrong, because we are telling the compiler that Cat
has an Animal
type inside itself! which means a cat has another animal inside itself! by this way, we can access all private members of Cat
from Animal
class. It looks like a cat which eats an animal (a mouse) and that animal (which is a mouse) can see all private parts of that cat (such as cat's stomach)!