Yaroslav
Yaroslav

Reputation: 205

Forward declaration within class in C++

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.

Upvotes: 4

Views: 1563

Answers (1)

Christian Hackl
Christian Hackl

Reputation: 27548

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.

Upvotes: 3

Related Questions