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

139 views Asked by At

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

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

2

There are 2 answers

6
463035818_is_not_an_ai On BEST ANSWER

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.

0
Evg On

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