3

In what cases it could be invalid to write Type *p = nullptr;

whereas only class Type *p = nullptr; is satisfying?

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
Max Popov
  • 357
  • 2
  • 12

2 Answers2

7

You need it when the type Type is shadowed by the name of a variable:

class Type{};

int main() {
    int Type = 42;

    //Type * p = nullptr; // error: 'p' was not declared in this scope
    class Type* p = nullptr;
}

However, as pointed out by Ayxan Haqverdili, ::Type* p = nullptr; works as well and has the added benefit of also working with type aliases.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
2

In addition to another answer, an elaborated type specifier forward declares a name, so you can write:

// class Type1 {};
Type1 *p = nullptr;         // error: 'Type1' was not declared in this scope

// class Type2 {};
class Type2 *p = nullptr;   // compiles

This could also be useful when you declare functions in headers:

void foo(class Type*);   // no separate forward declaration of Type is needed
Evg
  • 25,259
  • 5
  • 41
  • 83