c++classelaborated-type-specifier

When I should add the word "class" creating pointer in C++?


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

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


Solution

  • 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.