c++ – The class keyword before the member class

Question:

Whether the class keyword before the member class is treated as a kind of forward declaration of the class so that the compiler doesn't have to worry about what the "identifier" is.


Are these pieces of code identical?

class Foo
{
private:
    class Bar* a;
};  

and

class Bar;
class Foo
{
private:
    Bar* a;
};

Answer:

Yes, they are identical.

According to 3.3.2 Point of declaration [basic.scope.pdecl],
for such declarations, which are named elaborated-type-speci fi er , the name is declared in the outer scope.

This can be demonstrated with the following code:

struct Foo {
    struct Bar* a;
};

struct Bar {};

int main() {
    Bar b;
    Foo f;
    f.a = &b;
}

However, for declarations like class name; , the name is declared in the same scope, for example

struct Foo {
    struct Bar;
};

struct Foo::Bar {};
Scroll to Top