Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward declaration within class in C++

Tags:

c++

c++11

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.

like image 338
Yaroslav Avatar asked Oct 23 '25 14:10

Yaroslav


1 Answers

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.

like image 82
Christian Hackl Avatar answered Oct 26 '25 04:10

Christian Hackl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!