Reputation: 12616
This one doesn't 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 would work.
Why doesn't it work? It's not as though I'm exporting a nested class through a public method? It's just a private method returning a pointer to a private class. Any ideas?
Thanks!
Fixed the semi-columns. They're not the problem. Neither is writing class
in front of NestedClass.
Here's the error message:
MainClass.h: In function 'MainClass::NestedClass* getNestedClassFor(int i)':
MainClass.h:39: error: 'class MainClass::NestedClass' is private
MainClass.cpp:49: error: within this context
Here's the part of the .cpp file that's also complaining:
class MainClass::NestedClass * getNestedClassFor(int i) //Line 49
{
return NULL;
}
Upvotes: 6
Views: 2058
Reputation: 12616
Had forgotten to add the class scope in the .cpp, i.e.
class MainClass::NestedClass * getNestedClassFor(int i)
{
//...
}
Should be
class MainClass::NestedClass * MainClass::getNestedClassFor(int i)
{
//...
}
Stupid me!
Upvotes: 4
Reputation: 2268
one error is: (In fact it is not a error, just a stylish, see comments bellow)
class NestedClass * getNestedClassFor(int i);
should be only:
NestedClass * getNestedClassFor(int i);
Another is: when you declare a nested class, you should finish the declaration with a ";"
private:
class NestedClass
{
...
};
May be there has another errors there...
Upvotes: 2
Reputation: 1487
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;
}
Upvotes: 3
Reputation: 9340
Why doesn't it work? It's not as though I'm exporting a nested class through a public method? It's just a private method returning a pointer to a private class. Any ideas?
The compiler message is very clear. You're returning a pointer to a private nested class. The called of this function would then need to know the structure of this class, however since the class is private, then getting the structure is prohibited. You should private some of the class' attributes and methods, not the class itself. Even so, if you make all attributes and methods private then this class would have no use case.
What are you trying to achieve anyway?
Upvotes: 0
Reputation: 41
Why would you want to do it? You shouldn't expose private stuff to outside clients. That's the whole point of encapsulation. Make it public if it's needed to be accessible from outside.
Upvotes: 1