It is not possible to make a private method in C ++ return a pointer to a private nested class

This compiler does not want to compile:

class MainClass { public: ... private: class NestedClass { //Line 39 ... }; class NestedClass * getNestedClassFor(int i); }; 

The compiler says:

error: 'class MainClass :: NestedClass' is private

However, if I made NestedClass public , it will work.

Why is this not working? Is it not as if I were exporting a nested class through a public method? This is just a private method that returns a pointer to a private class. Any ideas?

Thanks!

Update

Fixed half columns. They are not a problem. Do not write class before NestedClass.

This is where the error message appears:

MainClass.h: In the function 'MainClass :: NestedClass * getNestedClassFor (int i)':

MainClass.h: 39: error: 'class MainClass :: NestedClass' is private

MainClass.cpp: 49: error: in this context

Here is the part of the .cpp file that also complains:

 class MainClass::NestedClass * getNestedClassFor(int i) //Line 49 { return NULL; } 
+6
source share
5 answers

Forgot to add class scope to .cpp, i.e.

 class MainClass::NestedClass * getNestedClassFor(int i) { //... } 

Must be

 class MainClass::NestedClass * MainClass::getNestedClassFor(int i) { //... } 

Stupid me!

+3
source

This compiles and works fine:

 class A { private: class B { public: B() {}; }; B *b; B *getB(); public: A(); }; A::A() { b = getB(); } A::B* A::getB() { A::B *tmp = new A::B(); return tmp; } int main() { A a; return 0; } 
+3
source

one mistake: (This is actually not a mistake, just stylish, see comments below)

 class NestedClass * getNestedClassFor(int i); 

should only be:

  NestedClass * getNestedClassFor(int i); 

Another: when you declare a nested class, you must end the declaration with ";"

 private: class NestedClass { ... }; 

Perhaps there are other errors there ...

+2
source

Why would you do this? You should not expose private items to external clients. This is the whole point of encapsulation. Make it public if it should be accessible from the outside.

+1
source

Why is this not working? Is it not as if I were exporting a nested class through a public method? This is just a private method that returns a pointer to a private class. Any ideas?

The compiler message is very clear. You are returning a pointer to a private nested class. This function called must then know the structure of this class, however, since the class is private, then obtaining the structure is prohibited. You should use some class attributes and methods, not the class itself. However, if you make all attributes and methods private, then this class will not have any use.

What are you still trying to achieve?

0
source

Source: https://habr.com/ru/post/906915/


All Articles