my question is how often do You really use nested classes in Your practice and in which cases? what is the real power of the nested classes, what can't be done without them?
P.S. please don't explain what is it, I know it (from technical point of view
)
views:
155answers:
4I usually use nested classes to embed finders objects (to use with std::find_if
) into my specific types.
Something like:
// Dummy example
class Foo
{
public:
class finder
{
public:
finder(int value) : m_value(value) {};
bool operator()(const Foo& foo) { return (foo.m_int_value == value); }
private:
int m_value;
};
private:
int m_int_value;
friend class finder;
};
Then:
vector<Foo> foo_list;
vector<Foo>::iterator foo =
std::find_if(foo_list.begin(), foo_list.end(), Foo::finder(4));
This could of course be done without the use of nested classes. But I find it quite elegant because the finder has no use outside of the class definition:
If I ever delete the class in case of code-refactoring the finder should be deleted as well.
They're useful when a class needs to contain grouped/encapsulated data. You can devise it all into a private
nested class to prevent unintentional use of the data type by the outside world.
It can also be used as a possibly clearer way to accomplish friendship. By nesting the class instead of using friendship you further encapsulate the friend
relationship between the code parts.
I use them rarely for the following reasons:
- They tend to be implementation details which I don't like to have in the header file.
- I don't like the syntax.
Sometimes I use embedded structs (for POD, no methods).
I use them as utility classes that need to access my class: signal handlers, timers, especially when using pimpl, so the implementation is already in a cpp-file.
There is nothing in C++ that can't be done without nested classes, but it is a nice way to scope-limit these classes that mostly just dispatch events to my class.