Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't make a private method in C++ return a pointer to a private nested class

Tags:

c++

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!

Update

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;
}
like image 282
Albus Dumbledore Avatar asked Jan 26 '12 09:01

Albus Dumbledore


2 Answers

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!

like image 139
Albus Dumbledore Avatar answered Oct 21 '22 03:10

Albus Dumbledore


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;
}
like image 39
Pietro Lorefice Avatar answered Oct 21 '22 03:10

Pietro Lorefice