-5

I am unsure about the order of declaration in my class. My compiler says error: "Foo" was not declared in this scope. If I change the order of public and private parts of the class, I end up with the same error. Also, if I want to use the getFoo(), and I am including my header file, the struct Foo type is not visible because it's private. But if I put it in public scope again, then public would have to come before private because otherwise the declaration of myFoo of type Foo can't happen since Foo was not decalred yet. I am confused here... thanks for your help!

/*MyClass.h*/

class MyClass
{


private:

 struct Foo{
  int bar;
 };

Foo myFoo;


public:
 Foo getFoo(){ return myFoo;}

};
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
tzippy
  • 6,458
  • 30
  • 82
  • 151

2 Answers2

3

It has nothing to do with public or private. Your inner type has to be defined before it is used:

struct Foo
{
  Bar bar() { return Bar(); } // ERROR
  struct Bar {};
};

struct Foo
{
  struct Bar {};
  Bar bar() { return Bar(); } // OK
};

Note: there has been some confusion concerning the accessibility of a private type. THe type is accessible outside of its class, it just cannot be named. So, this code that accesses the private type is completely legal:

class Foo
{
    struct Bar { 
        void do_stuff() const {}
    };

public:
    Bar bar() { return Bar(); } // OK
};
int main() 
{
    Foo f;
    f.bar().do_stuff(); // use temporary Bar object

    // In C++11, you can even make a named instance
    auto b = f.bar();   // instantiate a Bar object called b
    b.do_stuff();       // use it
}
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
-1

Your struct Foo should be public otherwise getFoo getter will not work as Foo is accessible only inside your class

nib
  • 700
  • 8
  • 15