17

I want to construct an object in the stack, using C++. Do you know what is the difference between these two ways of calling the constructor (with and without parenthesis):

a) MyClass object ;

b) MyClass object() ;

I am using MFC and when constructing the global variable for the main app, if I use the latter way, I get an exception, I thought these two ways were equivalent.

Thank you guys for any information.

Kemin Zhou
  • 6,264
  • 2
  • 48
  • 56
lurks
  • 2,576
  • 4
  • 30
  • 39

2 Answers2

30

This is one of those gotchas of C++.

MyClass object();

is the way that a function prototype is defined in C++, so the compiler thinks you are trying to declare another function in the middle of another function.

If you want to invoke the default constructor (i.e. the one which takes no arguments), use this syntax instead:

MyClass object;

See also Garth Gilmour's answer to the now-deleted question What is your (least) favorite syntax gotcha?:

In C++

Employee e1("Dave","IT"); //OK
Employee e2("Jane"); //OK
Employee e3(); //ERROR - function prototype
Mark Amery
  • 143,130
  • 81
  • 406
  • 459
LeopardSkinPillBoxHat
  • 28,915
  • 15
  • 75
  • 111
  • 2
    The `()` initializer in C++ is not necessarily an invocation of default constructor. `()` initializer performs value-initialization which is not equivalent to default constructor invocation, i.e. the last form (without `()`) is not equivalent to the intent expressed in the first one. The proper way to work arount "prototype" problem is to use copy-initialization syntax `MyClass object = MyClass()` and hope that the compiler will translate it into efficient code. – AnT stands with Russia Feb 22 '10 at 04:21
9

For example:

class MyClass
{
   public:
   MyClass()
   {x = 0;}
   MyClass(int X)
   {x = X;}
   private:
   int x;
};

int main()
{
   MyClass myObject(56); // initialize x to value '56'
   MyClass myObject2; //calls default constructor and initializes x to 0
   return 0;
}
cpx
  • 17,009
  • 20
  • 87
  • 142