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?
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.
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.
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. };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With