1

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 expected. Also, this problem only applies to the default constructor. I would like to understand why.

using namespace std;
#include <iostream>

class Student {

  public:

    int gpa;

    Student() { 
      gpa = 4;
    }

    Student( int x ) { 
      gpa = x; 
    }

};

int main() {

  Student zero;
  Student sally( 2 ); 
  Student jack();

  cout << zero.gpa << endl; //prints 4
  cout << sally.gpa << endl; // prints 2
  cout << jack.gpa << endl; //error: request for member 'gpa' in 'jack', which is of non-class type 'Student()'

}
Kacy Raye
  • 1,312
  • 1
  • 11
  • 14

5 Answers5

8

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.

sasha.sochka
  • 14,395
  • 10
  • 44
  • 68
6
  Student jack();

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

See more in this gotw

Balog Pal
  • 16,195
  • 2
  • 23
  • 37
3

"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#. :-)

Steve
  • 726
  • 4
  • 10
2

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.

Baltasarq
  • 12,014
  • 3
  • 38
  • 57
0

I would try this

class Student {

public:

int gpa = 4;

Student() { };
GManika
  • 505
  • 1
  • 6
  • 13