Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 593
Samaursa Avatar asked Dec 19 '10 07:12

Samaursa


People also ask

How is a nested class defined?

A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.

How do you declare a nested class in C++?

Nested Classes in C++ A nested class is a class that is declared in another class. The nested class is also a member variable of the enclosing class and has the same access rights as the other members. However, the member functions of the enclosing class have no special access to the members of a nested class.


1 Answers

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. }; 
like image 68
sje397 Avatar answered Sep 23 '22 17:09

sje397