Search code examples
c++inner-classesmember

Nested Class Definition in source file


If I have a nested class like so:

  class MyClass
  {
    class NestedClass
    {
    public:
      // nested class members AND definitions here
    };

    // main class members here
  };

Currently, the definitions of MyClass are in the CPP file but the definitions for NestedClass are in the header file, that is, I cannot declare the functions/constructors in the CPP file.

So my question is, how do I define the functions of NestedClass in the cpp file? If I cannot, what is the reason (and if this is the case, I have a vague idea of why this happens but I would like a good explanation)? What about structures?


Solution

  • You can. If your inner class has a method like:

      class MyClass   {
        class NestedClass
        {
        public:
          void someMethod();
        };
    
        // main class members here
      };
    

    ...then you can define it in the .cpp file like so:

    void MyClass::NestedClass::someMethod() {
       // blah
    }
    

    Structures are almost the same thing as classes in C++ — just defaulting to 'public' for their access. They are treated in all other respects just like classes.

    You can (as noted in comments) just declare an inner class, e.g.:

    class MyClass   {
        class NestedClass;
        // blah
    };
    

    ..and then define it in the implementation file:

    class MyClass::NestedClass {
      // etc.
    };