views:

2594

answers:

3
   class Outer {

      class Inner {
          public:
              Inner() {}
              void func() ;
      };

  private:
      static const char* const MYCONST;
      int var;

  };

  void Outer::Inner::func() {
      var = 1;
  } 

  const char* const Outer::MYCONST = "myconst";

This errors out when I compile with class Outer::Inner' has no member named `var'

+2  A: 

Anything that is part of Outer should have access to all of Outer's members, public or private.

Edit: your compiler is correct, var is not a member of Inner. But if you have a reference or pointer to an instance of Outer, it could access that.

Mark Ransom
+8  A: 

An inner class is a friend of the class it is defined within.
So yes an object of type Outer::Inner can access the member variable var of an object of type Outer.

Unlike Java though there is no corelation between an object of type Outer::Inner and an object of the parent class. You have to make the parent child relationship manually.

#include <string>
#include <iostream>

class Outer
{
    class Inner
    {
        public:
            Inner(Outer& x): parent(x) {}
            void func()
            {
                std::string a = "myconst1";
                std::cout << parent.var << std::endl;

                if (a == MYCONST)
                {   std::cout << "string same" << std::endl;
                }
                else
                {   std::cout << "string not same" << std::endl;
                }
            }
        private:
            Outer&  parent;
    };

    public:
        Outer()
            :i(*this)
            ,var(4)
        {}
        Outer(Outer& other)
            :i(other)
            ,var(22)
        {}
        void func()
        {
            i.func();
        }
    private:
        static const char* const MYCONST;
        Inner i;
        int var;
};

const char* const Outer::MYCONST = "myconst";

int main()
{

    Outer           o1;
    Outer           o2(o1);
    o1.func();
    o2.func();
}
Martin York
Technically in the current C++ standard, a nested class does NOT have special access to its enclosing class. See sec 11.8.1 of the standard. HOWEVER see also this standard defect: http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#45
Greg Rogers
For what its worth, GCC follows the proposed resolution given there, other compilers probably do too.
Greg Rogers
+2  A: 

An inner class has access to all members of the outer class, but it does not have an implicit reference to a parent class instance (unlike some weirdness with Java). So if you pass a reference to the outer class to the inner class, it can reference anything in the outer class instance.

MSN