FAQ 19.13 What is a private class?

A private class is a class created only for implementation purposes and is hidden from normal users. Typically, all its constructors (and often all its other members as well) are private: and it declares another class as its friend. Because the private class lacks public: constructors or member functions, only the designated friends and other instances of the private class can create or use instances of the private class.

For example, the Node class associated with a linked list class might be so specialized that no other class would benefit from reusing it. In this case the Node class can be a private class and can declare the linked list class as a friend. In the following code, class Node is nested inside class List. Although not strictly part of the private class concept, this technique has the further benefit of reducing the number of names in the outer namespace (nesting Node inside List removes the name Node from the namespace that List is in).

 #include <new> #include <cstdlib> using namespace std; class List { public:   List()                          throw();   List(const List& a)             throw(bad_alloc);  ~List()                          throw();   List& operator= (const List& a) throw(bad_alloc);   void prepend(int e)             throw(bad_alloc);   bool isEmpty() const            throw();   void clear()                    throw(); private:   class Node;                                        <-- 1   Node* first_; }; class List::Node { private:                                             <-- 2   friend List;                                       <-- 3   Node(int e, Node* next=NULL) throw();   Node* next_;   int   elem_; }; List::Node::Node(int e, Node* next) throw() : next_(next), elem_(e) { } List::List()               throw()          : first_(NULL) { } List::List(const List& a)  throw(bad_alloc) : first_(NULL) { *this = a; } List::~List()              throw()          { clear(); } void List::prepend(int e)  throw(bad_alloc) { first_ =                                               new Node(e, first_); } bool List::isEmpty() const throw()          { return first_ == NULL; } int main() {   List a;   a.prepend(4);   a.prepend(3);   a.prepend(2);   List b;   b = a; } 

(1) The private class is called List::Node

(2) List::Node has no public: members

(3) List::Node declares List as its friend



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net