开发者

Difference between declaring a C++ object with/without braces [duplicate]

This question already has answers here: Closed 11 years ago.

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.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜