-4

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
{

};
Robust
  • 67
  • 11
  • 2
    This is called a "nested class" not a "subclass". Use accepted terminology if you want to be understood. – n. m. could be an AI Jul 13 '14 at 11:26
  • http://stackoverflow.com/questions/11398122/what-are-the-purposes-of-inner-classes – Adam Burry Jul 13 '14 at 11:28
  • Oh come on people if you do not know the real answer you down vote the question and the link you provide does not correlate to the question I am asking here..I am asking if anyone has ever found any use of nested classes in C++ ...What was the need of it ? what is that something special for which they were designed ? If you cannot answer it you just down vote it great .. – Robust Jul 13 '14 at 11:33
  • http://stackoverflow.com/questions/216748/pros-and-cons-of-using-nested-c-classes-and-enumerations – Adam Burry Jul 13 '14 at 11:33
  • @AdamBurry The first is a Java question. – Shoe Jul 13 '14 at 11:34
  • The reasons for inner/nested classes are the similar in C++, Java, C#, etc. – Adam Burry Jul 13 '14 at 11:36

2 Answers2

1

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.

Moo-Juice
  • 38,257
  • 10
  • 78
  • 128
0

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)!

Sadeq
  • 7,795
  • 4
  • 34
  • 45