views:

315

answers:

5

This code doesn't behave how I expect it to.

#include<iostream>
using namespace std;

class Class
{
    Class()
    {
        cout<<"default constructor called";
    }

    ~Class()
    {
        cout<<"destrutor called";
    }
};

int main()
{    
    Class object();
}

I expected the output 'default constructor called', but I did not see anything as the output. What is the problem?

+16  A: 

No call to constructor

Because the constructor never gets called actually.

Class object(); is interpreted as the declaration of a function object taking no argument and returning an object of Class [by value]

Try Class object;

EDIT:

As Mike noticed this is not exactly the same code as what you are feeding to the compiler. Is the constructor/destructor public or is Class a struct?

However google for C++ most vexing parse.

Prasoon Saurav
Got to the answer a moment before me _and_ reformatted the post. +1
JoshD
Thanks @JoshD :)
Prasoon Saurav
+22  A: 

Nope. Your line Class object(); Declared a function. What you want to write is Class object;

Try it out.

You may also be interested in the most vexing parse (as others have noted). A great example is in Effective STL Item 6 on page 33. (In 12th printing, September 2009.) Specifically the example at the top of page 35 is what you did, and it explains why the parser handles it as a function declaration.

JoshD
At least give him the name of the problem so he can google it!
Martin York
+1, btw Visual C++ issues `warning C4930: prototyped function not called (was a variable definition intended?)` in such cases.
sharptooth
Is that really the "most vexing parse," though? I always thought the phrase referred to the more frustrating problem, that `T x(T())` is a function declaration.
James McNellis
@James McNellis: That's what Scott Meyers called it. I don't exactly agree, and I didn't even connect this question with it immediately. I think your example is much more common and frustrating.
JoshD
A: 

You can use it like this:

Class obj;
//or
Class *obj = new Class(/*constructor arguments*/);
Hitman_99
Second one is wrong.
GMan
Second one should be `Class *obj = new Class(/*args*/);`.
JoshD
Yeah, my bad :)
Hitman_99
A: 

a constructor is called when an object is created, in your code where is that object ??? you declared a function object() with return type Class

BhargavSushant
A: 

Because you didn't declare an object in main.

Ahmed
Correct, but not helpful to someone who thinks they did declare an object.
Kate Gregory