'class' keyword in variable definition in C++

前端 未结 3 1331
天命终不由人
天命终不由人 2020-12-17 10:59

Before anyone asks, yes, this is part of a homework, and yes, I did a lot of Googling before asking. I spent the last hour searching intensively on Google with many, many di

相关标签:
3条回答
  • 2020-12-17 11:05

    An elaborated type specifier is a type name preceded by either the class, struct, enum, or union keyword.

    class identifier 
    struct identifier 
    enum identifier 
    union identifier
    

    An elaborated type specifier is used either for emphasis, or to reveal a type name that is hidden by the declaration of a variable with the same name in the same scope.

    source

    0 讨论(0)
  • 2020-12-17 11:19

    Actually it is optional to use class while creating object of class. In C language it is compulsory to use struct in front of struct name to create its variable. As C++ is superset of C. There is only one difference between struct and class in C++, and that is of access modifier.

    To keep backward compatible it is permissible.

    So,

    class MyClass* myClass = new MyClass();
    

    And,

    MyClass* myClass = new MyClass();
    

    Both are same.

    0 讨论(0)
  • 2020-12-17 11:23

    The words "inline forward declaration" need to be mentioned here!

    A forward declaration is simply a way to tell the compiler about a type name before its actually defined. You find these in header files all the time.

    // MyStruct.h
    class MyClass;
    
    struct MyStuct {
       MyClass* m_myClass;
       void foo();
    }
    
    // MyStruct.cpp
    #inlude "MyClass.h"
    void MyStruct::foo() { m_myClass->SomeFunc(); }
    

    Notice that the header file only declares MyClass as a class identifier, and has no idea what it actually is until its defined via the #include in the cpp file. This is forward declaration.

    inline forward declaration is really the same thing, but you simply do it all on one line. This is the same exact code achieving the same thing.

    // MyStruct.h
    struct MyStuct {
       class MyClass* m_myClass;
       void foo();
    }
    
    // MyStruct.cpp
    #inlude "MyClass.h"
    void MyStruct::foo() { m_myClass->SomeFunc(); }
    

    I feel like most programmers prefer the standard forward declaration method (less typing overall usually). Which is why it can be confusing when stumbling upon the lesser used inline version.

    I see many of the answers here calling it an optional keyword, but in the above context of inline forward declaration, it is very much not optional, and will result in compile errors due to missing type specifier.

    0 讨论(0)
提交回复
热议问题