C++ Internal Classes

C++, like Java, allows you to have internal classes. You can implement them by simply including the class in the .cpp file and not in the header file. Yep, its that simple. If you try this you will probably realise that you cant include the class as a data member. This is because when you try to include it in the class the internal class hasn’t been declared yet. That’s easy to fix, you can prototype a class by simply adding class ClassName;. Why am I telling you this? Because its an interesting design pattern, and that inner class is called a “Cheshire Class”.

The Cheshire Class is a hidden internal class. This doesn’t immediately sound useful, until you think about how C++ handles private variables. When you add a private variable to a class, even though it is not visible to the calling application, it still affects the structure of the class and hence all the code that links against it will need to be recompiled. The Cheshire class prevents this by keeping all your private variables in a private internal class. See this Example:

outerclass.h

#ifndef OUTERCLASS_H_
#define OUTERCLASS_H_

class InnerClass;

class OuterClass {
private:
  InnerClass *internal;
public:
  OuterClass();
  virtual ~OuterClass();
};

#endif /* OUTERCLASS_H_ */

outerclass.cpp

class InnerClass {
public:
  int privateVariable;
};
OuterClass::OuterClass() {
  internal.privateVariable = 0;
}

OuterClass::~OuterClass() {

}

Now instead of adding new private data to the outer class, you add it to the inner class. This way your header stays the exact same, the data structure never changes.

Note that this does take up more space, and takes a little longer to resolve because it has to jump via and extra pointer but sometimes it is worth it for that nicer solution.
Random Thought: Which is more valuable, bread or gold? Why? Which is more useful?