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?
“Chesire Class”? You totally made that up, and didn’t compile the example.
“InnerClass internal;” needs to be a pointer as the compiler hasn’t seen its definition and doesn’t know its size.
Also, the virtual keyword is only used in the declaration (.h), not the definition (.cpp).
This is the Pimpl (Pointer to Implementation) Idiom. http://www.c2.com/cgi/wiki?PimplIdiom
Cheers for the double checking. And you are completely right I should have compiled it first. I’ve corrected the post.
As your link points out its also called the ‘Cheshire Cat Technique’ with the inner class being called the cheshire class, and the pointer being called the smile.