7

Possible Duplicate:
Error on calling default constructor with empty set of brackets

I have a testing program attached. Question:

If I declare like the following, there is no objected created and the default constructor is not called. 'grCell c3();' // bad

However, Declare like this is OK. An object is created and its constructor is called. 'grCell c1;' // good

What is the difference between 'grCell c3()' and 'grCell c1' ?

Thanks!

Todd

//---- BEGIN -------

#include <iostream>
#include <cstdio>

typedef unsigned int uint;
using namespace std; 

//
class grCell {
 public:
  grCell()      { printf("HERE_0\n"); };
  grCell(int i) { printf("HERE_1\n"); };
  ~grCell() {};

  void setX(int x) { _x = x; }
  //
  //
private:


  int  _x:22;
};

int main()
{

  grCell c1;  // good
  c1.setX(100);


  grCell c3();  // bad
  c3.setX(100);

  grCell c2(5);
  c2.setX(10);


} 

//------ END ------

Community
  • 1
  • 1
user1273456
  • 71
  • 1
  • 3

2 Answers2

7

What is the difference between grCell c3() and grCell c1 ?

The first declares a function while the second creates an object named c1 of the type grCell.

grCell c3();

It does not create an object but declares a function with the name c3 which takes no arguments and returns an object of type grCell.
It is the Most vexing parse in C++.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • and then of course the *next* line causes a compiler error because the `c3` function doesn't have a `setX()` member. – Greg Hewgill Sep 18 '12 at 04:41
5

You have encountered the most vexing parse.

grCell c3() declares a function named c3 which returns a grCell.

grCell c3 declares an instance of grCell named c3.

In C++, there is a saying, "anything the looks like a function, is a function".

Concerning the comment

grCell() is called value initialization, both grCell() and grCell invoke the default constructor if it is class type. However, int() and int are different, the first version zero initializes the object.

Jesse Good
  • 50,901
  • 14
  • 124
  • 166
  • grCell *p1 = new grCell(); // OK grCell *p2 = new grCell; // OK – user1273456 Sep 18 '12 at 04:50
  • @user1273456: `new` is a C++ keyword, and `new grCell()` is on the right hand side of an expression which uses `operator=`, it is impossible to treat that as a function. – Jesse Good Sep 18 '12 at 04:52
  • @JesseGood Can you please tell me the difference between `new grCell()` and `new grCell`? I am pretty new to C++ btw. – Suri Jan 17 '21 at 00:43
  • @Suri: [See this question](https://stackoverflow.com/questions/1581763/difference-between-a-pa-new-a-and-a-pa-new-a) which explains it. – Jesse Good Jan 17 '21 at 21:10