sji
sji

Reputation: 1907

How do you define the implementation of function nested class outside of the function?

I have code like this:

class A {
  void foo() {
    class B {
      void bar() { std::cout << "Bar!" << endl; }
    };
    B b;
  }
};

However I would like to implement the struct B outside of the function scope. If this was just a nested class in A I could do something like:

class X {
  void foo();
  class Y;
}
class X::Y {
  void bar() { std::cout << "Bar!" << endl; }
}

But I cannot work out if it is possible to do a similar thing for class B. The compiler tells me that the type of that class is A::foo::B but if I attempt to define that class I am told that foo is not a member of A:

An attempt:

class A {
  void foo();
};

class A::foo::C {
  void bar() { std::cout << "Bar!" << std::endl; }
};

void A::foo()  {
  class C;
  C c;
  c.bar();
}

Errors:

test.cpp(15) : error C3083: 'foo': the symbol to the left of a '::' must be a type
test.cpp(15) : error C2039: 'C' : is not a member of 'A'
    test.cpp(6) : see declaration of 'A'
test.cpp(19) : error C2079: 'c' uses undefined class 'A::foo::C'

Upvotes: 2

Views: 92

Answers (1)

That is not possible. The name C is not visible outside of the scope of the function foo. And unlike for classes, there is now way to reach into a function scope from outside that function.

Notice that A is totally irrelevant in your example. If foo was a namespace-scope function, the result would be exactly the same.

If you want a function-local class, you have to implement it entirely inside that function.

Upvotes: 2

Related Questions