Louen
Louen

Reputation: 3677

Forward declaration syntaxes have different behavior

When forward declaring the member of a class, you can either do class Bar; Bar* m_baror the shorter class Bar* m_bar. But the name resolution seems to behave differently.

For example this compiles perfectly:

struct Foo {
  Foo();
  struct Bar;
  Bar* m_bar;
  struct Bar {
      int m_baz;
  };
};

Foo::Foo(){
    m_bar = new Foo::Bar;
}

While this doesn't, because the compiler thinks the type of m_baris not Foo::Bar but just Bar :

struct Foo {
  Foo();
  struct Bar* m_bar;
  struct Bar {
      int m_baz;
  };
};

Foo::Foo(){
    m_bar = new Foo::Bar;
}

My question is more out of curiosity than an actual problem (and I know forward declaration and nested classes are a touchy subject in C++), but why does the compiler interprets the second version as a global name ?

Upvotes: 3

Views: 89

Answers (1)

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 506945

The spec says this in 3.3.2p6bullet2 (it actually just says into what scope the name declared is added to. If I remember correctly, there is no explicit rule that says that the class is a member of that namespace).

I think that this is an important C compatibility feature. If it wasn't this way, the class would be global in C, but a class member in C++.

Upvotes: 2

Related Questions