39

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?

Peter - Reinstate Monica
  • 15,048
  • 4
  • 37
  • 62
Samaursa
  • 16,527
  • 21
  • 89
  • 160

1 Answers1

68

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.
};
sergiol
  • 4,122
  • 4
  • 47
  • 81
sje397
  • 41,293
  • 8
  • 87
  • 103
  • What do you mean by "not ... like other inner classes"? – Cheers and hth. - Alf Dec 19 '10 at 07:49
  • @Alf: where did I write 'not'? – sje397 Dec 19 '10 at 08:05
  • Sorry, my eyes evidently crossed or something. Still wondering what you mean by the last sentence, though. I mean, an inner class does not need to be defined within the outer class (e.g. the ordinary PIMPL idiom relies on that). And that seemingly contradicts what you write in last sentence, so possibly you mean something else than what's literally written? Cheers, – Cheers and hth. - Alf Dec 19 '10 at 08:32
  • @Alf: I'll admit I'm not terribly familiar with the PIMPL idiom (or at least, that terminology) - but from what I can see, it's usually about including a pointer to a private implementation, not an inner class? – sje397 Dec 19 '10 at 09:04
  • 1
    The private implementation is usually an inner class, which is just declared. – Cheers and hth. - Alf Dec 19 '10 at 09:08
  • The declaration followed by in-cpp definition just gives me errors all over. For example "undefined type" errors when trying to use an inner-declared cpp-defined nested struct in a priority_queue. Defining the struct in the header file gives no error... – Noein May 10 '15 at 19:16
  • @Noein You need to qualify definitions with the class name and that of the parent it's nested in. There's certainly questions on this site that will cover that. – sje397 May 10 '15 at 21:28