Class Etiquette

Started by
1 comment, last by riku 15 years, 1 month ago
Is it right to put a class within a class?, ie ... Class Face { public: Class Eyes { } }
Advertisement
You can. This would imply to the average reader that there's a specific kind of eyes known as "face eyes", which are distinct from other, non-face kinds of eyes. It's not really that useful, though.
I use inner classes regularly. They can used to improve encapsulation.

Their advantage over non-inner classes is that they can access the outer class' private members in many languages (no "friend" relation needed). You can also make the inner class private in the outer class, so it cannot be used outside of the outer class (and it's friends).

I also use forward declared inner classes in C++, in particular with the Pimpl idiom.

// Header fileclass Pimpl{    public:    private:        struct impl_t; // put all private members here        impl_t *impl;  // and use them through this pointer };// Implementation file#include <nastyplatformheader.h>  // we don't want this in the header filestruct Pimpl::impl_t{    NastyPlatformSpecificThing thing;};Pimpl::Pimpl() : impl(new impl_t){    impl->thing = createThing();}Pimpl::~Pimpl(){    delete impl;}


This has the obvious advantage of not having to include implementation specific header files in our header. You can also have multiple implementations of the same routines using the same header files. For example, you can have a single set of header files for a library that has implementation files for Windows and Linux and let your build system decide which to use.

-Riku




This topic is closed to new replies.

Advertisement