Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't C++ need forward declarations for class members?

I was under the impression that everything in C++ must be declared before being used.

In fact, I remember reading that this is the reason why the use of auto in return types is not valid C++0x without something like decltype: the compiler must know the declared type before evaluating the function body.

Imagine my surprise when I noticed (after a long time) that the following code is in fact perfectly legal:

[Edit: Changed example.]

class Foo
{
    Foo(int x = y);
    static const int y = 5;
};

So now I don't understand:

Why doesn't the compiler require a forward declaration inside classes, when it requires them in other places?

like image 485
user541686 Avatar asked Sep 09 '11 04:09

user541686


2 Answers

The standard says (section 3.3.7):

The potential scope of a name declared in a class consists not only of the declarative region following the name’s point of declaration, but also of all function bodies, brace-or-equal-initializers of non-static data members, and default arguments in that class (including such things in nested classes).

This is probably accomplished by delaying processing bodies of inline member functions until after parsing the entire class definition.

like image 100
Ben Voigt Avatar answered Sep 20 '22 00:09

Ben Voigt


Function definitions within the class body are treated as if they were actually defined after the class has been defined. So your code is equivalent to:

class Foo
{
    Foo();
    int x, *p;
};
inline Foo::Foo() { p = &x; }
like image 33
K-ballo Avatar answered Sep 19 '22 00:09

K-ballo