Inner class Vs new file

Any opinions about when to make an inner class and when a class "deserves" it's own file?

I've never made an inner class, they seem unwieldy to me.
One reason could be because it doesn't make sense to use the nested class on its own. You only care about Nodes when they're inside a List.
I sometimes feel using inner classes provide a higher degree of "associativeness/enclosure" for your code if inner object makes logical sense to be nested within outer.

Also circular references are automatically handle by inner-outer class design - ie you don't need forward class declarations.

Embedding an inner class within an outer class allows you to have more than one of the same name inner class due to the inner class being defined logically within context of outer class.

so.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Outer1
{
public:
   class Inner
   {
      ...  // implementation specific to context of Outer1
   };
};


class Outer2
{
public:
   class Inner
   {
       ...  // implementation specific to context of Outer2
   };
};


Last edited on
@SIK that's not the point of inner classes.

Inner classes are classes within the scope of another class, equivalent to Java's static inner classes. They are generally used as helper classes and are, in most instances, private or protected.

Consider a basic linked-list class; it may have a private Node structure in its scope:
1
2
3
4
5
6
7
8
9
10
11
template<typename T>
class LinkedList
{
    struct Node
    {
        T t;
        Node *next;
    };
public:
    //linked list implementation
};


There are other cases but the linked list & node case is the most obvious.
... er, not the point? Maybe you should reconsider your phrasing - it sounds pretty abrasive. I agree with SIK's usage since it allows you to be more visually explicit during object instantiation. But I think that we can all agree that usage is personal preference and there's no right or wrong, similar to use of global variables.
Last edited on
@L B: the general case as is with example of LinkedList is inline with my first point.

My third point highlights another benfit to be gained using inner classes. This becomes usefull when creating some type of template that requires template arguments of classes that has an Inner class.

This way the template code "lends" itself easier due to same inner class names expected and avoids having to pass through 2 template paramters which increases degree for error and also makes code more complex.
Topic archived. No new replies allowed.