4

I have a question about forward declaration in C++

class Outer::Inner; // not valid. error
class Outer {
    Inner * inn; // not valid, needs forward declaration.
    class Inner {
    }
}

But when implemented like this:

// class Outer::Inner; // not valid. error
class Outer {
    class Inner; // forward-"like" declaration within class
    Inner * inn;
    class Inner {
    }
}

Compiles ok. But I have never seen implementations like this before (because of my small experience in C++), so I'm interested in knowing if this won't cause some kind of error or unpredictable behaviour in the future.

quamrana
  • 37,849
  • 12
  • 53
  • 71
Yaroslav
  • 205
  • 3
  • 7
  • 1
    possible duplicate of [Forward declaration of nested types/classes in C++](http://stackoverflow.com/questions/951234/forward-declaration-of-nested-types-classes-in-c) – Sigve Kolbeinson Jul 27 '15 at 18:06
  • I believe you can also write `class Inner * inn;` to combine the forward declaration with the pointer declaration. – rlbond Jul 27 '15 at 18:10
  • I think it's not a duplicate. The OP apparently does not want to use the `Outer::Inner` syntax but wonders if a forward declaration of a nested class is allowed in the first place. – Christian Hackl Jul 27 '15 at 18:12
  • 1
    @rlbond No, that does a very different thing. – T.C. Jul 27 '15 at 18:15
  • Ah yeah, it seems to declare a class `B` that isn't in the scope of `A`. Unfortunate. – rlbond Jul 27 '15 at 19:11
  • Also note that since class `Inner` is declared in `Outer` it has access to its `private` parts which can be very useful to move implementation details into it (see the PImpl idiom and https://lanzkron.wordpress.com/2011/12/17/who-has-access-to-your-private-parts/) – Motti Jul 27 '15 at 20:04

1 Answers1

3

It's valid. The standard says:

9.7 Nested class declarations [class.nest]

If class X is defined in a namespace scope, a nested class Y may be declared in class X and later defined in the definition of class X (...).

The following example is given, too:

class E {
  class I1; // forward declaration of nested class
  class I2;
  class I1 { }; // definition of nested class
  };
class E::I2 { };

Source: C++11 draft n3242

E and I1 correspond to Outer and Inner in your question.

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62