Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ declare an object with parenthesis [duplicate]

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 ------

like image 357
user1273456 Avatar asked Sep 18 '12 04:09

user1273456


1 Answers

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++.

like image 192
Alok Save Avatar answered Nov 14 '22 06:11

Alok Save