In C language, structures can be defined inside structures, Similarly in C++, we can
have structures or classes defined inside classes. Classes defined within other classes are called nested classes.
A nested class is written exactly in the same way as a normal class. We write its data members, member functions, constructors and destructors but no memory is allocated for a nested class unless an instance of it is created. C++ allows multiple levels of nesting. Importantly, we should be clear about the visibility of the nested class. If a class is nested inside the public section of a class, it is visible outside the outer (enclosed) class. If it is nested in the private section, it is only visible to the members of the outer class. The outer class has no special privileges with respect to the inner class. So, the inner class still has full control over the accessibility of its members by the outer class. Interestingly, the friend operator can be used to declare enclosed class as a friend of inner class to provide access to inner class’s private members. This operator is used in the same way as we use it for other classes that are not nested. We can also make the inner class to access the private members of enclosed class by declaring the inner class as a friend of outer class. The reason of nesting classes within other classes is simply to keep associated classes together for easier manipulation of the objects.
No comments:
Post a Comment