What is the difference between Object b(); and Object b;?

后端 未结 5 1791
执念已碎
执念已碎 2021-01-23 07:49

To be more explicit, I get a compile time error when I try accessing an instance variable when I create an object using (), but when I don\'t, the code compiles and runs as expe

相关标签:
5条回答
  • 2021-01-23 08:28

    The problem is that Student jack(); declares a function with Student as a return type. It doesn't declare an object of that class as you expect.

    0 讨论(0)
  • 2021-01-23 08:33
      Student jack();
    

    declares a function that returns student and takes no arguments. Not an object!

    See more in this gotw

    0 讨论(0)
  • 2021-01-23 08:36

    What is the difference between Object b(); and Object b;?

    The difference exists because C++ interprets that as a function being declared, instead of an object being created.

    Object b;
    

    This is the object b of class Object being created by means of the default constructor.

    Object b();
    

    This is the function b(), being declared (it will be defined elsewhere) to return an object of class Object, and no parameters.

    Hope this helps.

    0 讨论(0)
  • 2021-01-23 08:41

    I would try this

    class Student {

    public:

    int gpa = 4;
    
    Student() { };
    
    0 讨论(0)
  • 2021-01-23 08:45

    "Object b();" declares a function b() returning an object of type Object, while "Object b;" defines a variable b of type Object.

    No, it's not obvious, and it still comes back to bite me if I switch between C++, Java, and C#. :-)

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