2

Possible Duplicate:
constructor invocation mechanism

It took me long to figure this problem. So I was curious to know the difference between them. Below is the code snippet:

struct Test
{
  Test () { cout<<" Test()\n"; }
 ~Test () { cout<<"~Test()\n"; }
};
int main()
{
  Test obj(); // Remove braces of 'obj' & constructor/destructor are printed
}

Wanted to know that, why such behavior ? Is there any fundamental difference between declaring an object with/without empty braces (here we talk only about the cases of default constructor). Code is compiled one of the latest versions of Ubuntu/g++. Sorry if, it's a repeat question.

Community
  • 1
  • 1
iammilind
  • 68,093
  • 33
  • 169
  • 336
  • 1
    This is a dupe! Check out [this thread](http://stackoverflow.com/questions/4283576/constructor-invocation-mechanism/) – Prasoon Saurav Mar 23 '11 at 04:26
  • 2
    Just as an aside, *braces* are `{}`, but *parentheses* are `()`. I couldn't figure out what you meant until I realised that you were talking about the `()`. – Greg Hewgill Mar 23 '11 at 04:35

2 Answers2

2
Test obj();

declares a function named obj that takes no parameters and returns an object of type Test. It does not create an object obj of type Test with the default constructor.

Jesse Beder
  • 33,081
  • 21
  • 109
  • 146
  • Oh.. thanks. I forgot that fundamental. I kept empty braces to emphasize that, this is indeed a default constructor to the viewer. But messed up with another (forward declaration) feature. :) I usually do this, with operator 'new Struct()', but missed that, we can't do it with stack objects. – iammilind Mar 23 '11 at 04:29
  • @prasoon, yes I see. Will try for it. – iammilind Mar 23 '11 at 04:34
0

Test obj(); means that declaring a function named obj() whose return type is Test. Statement is not actually instantiating class Test. For the class to be instantiated -

Test obj ; // obj is instantiated meaning it's constructor is called and 
           // destructor is called when gone out of scope.
Mahesh
  • 34,573
  • 20
  • 89
  • 115