Nested class are used for hiding implementation details, exactly hiding the classes.
PROS:
class List
{
public:
List(): head(NULL), tail(NULL) {}
private:
class Node
{
public:
int data;
Node* next;
Node* prev;
};
private:
Node* head;
Node* tail;
};
Here I don't want to expose Node as other people may decide to use the class and that would hinder me from updating my class as anything exposed is part of the public API and must be maintained forever. By making the class private, I not only hide the implementation I am also saying this is mine and I may change it at any time so you can not use it.
CONS:-
One more example,
Let's imagine the following code :
class List
{
public:
List(): head(NULL), tail(NULL) {}
private:
class Node
{
public:
int data;
Node* next;
Node* prev;
};
private:
Node* head;
Node* tail;
};
class A
{
public :
class B { /* etc. */ } ;
// etc.
} ;
Or even:
class A
{
public :
class B ;
// etc.
} ;
class A::B
{
public :
// etc.
} ;
So:
- Privilegied Access: A::B has privilegied access to all members of A (methods, variables, symbols, etc.), which weakens encapsulation
- A's scope is candidate for symbol lookup: code from inside B will see all symbols from A as possible candidates for a symbol lookup, which can confuse the code
- forward-declaration: There is no way to forward-declare A::B without giving a full declaration of A
- Extensibility: It is impossible to add another class A::C unless you are owner of A
- Code verbosity: putting classes into classes only makes headers larger. You can still separate this into multiple declarations, but there's no way to use namespace-like aliases, imports or usings.
Conclusion:-
As a conclusion, unless exceptions (e.g. the nested class is an intimate part of the nesting class... And even then...), the flaws outweighs by magnitudes the perceived advantages.
On the pro-side, you isolate this code, and if private, make it unusable but from the "outside" class...
-Coutesy : stackOverflow
------------------------------------------------------------------------------------------------------------
Reference link:- http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr061.htm
------------------------------------------------------------------------------------------------------------
Reference link:- http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr061.htm
No comments:
Post a Comment