Purpose of an inner class

One reason is that inner classes have access to the members of the enclosing class directly. They do not need a reference to the enclosing class in order to access those members. At the same time other objects may need access to the inner object.

I can think of the example of Iterators that are declared as inner classes in collections. The iterator needs to have intimate knowledge of the collection that it iterates but the client code needs access to the iterator itself as an object. You cannot take the functionality of the iterator and include it in the outer class.

Maybe the responsibilities of the outer class does not include those of the inner class directly. So creating the inner class helps to maintain highly cohesive classes.


Inner classes are very useful if they only pertain to their containing (or, outer) class.

A good example of a private inner class is when you need to manage something within the outer class that will never be exposed. In the example below, a cache manager handles caching and uncaching of objects. It uses a private inner class to store the pointer to an object that it wants to cache, and also the time it was last accessed. Code that users this hypothetical CacheManager need never know about CacheEntry.

class CacheManager
{
private:
    class CacheEntry
    {
    private:
        Object* m_pObjectToCache;
        int     m_nTicksSinceTouched;
    }; // eo class CacheEntry
    std::map<int, CacheEntry*> m_Cache;

public:
    Object* getObject(int _id);
}; // eo class CacheManager

Then comes the case for a public inner class. I would use a nested class if the name (which I would like to keep simple), my conflict elsewhere:

class Tree
{
public:
    // public class.. Node might pertain to anything in the code, let's keep it simple
    // and clear that THIS Node belongs and works with THIS Tree class.
    class Node
    {
    };// eo class Node
}; // eo class Tree