21

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?

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
mithilesh
  • 211
  • 1
  • 3
  • 2
    @dribeas: This isn't really the most vexing parse; it's just a slightly vexing parse. The "most vexing parse" is usually reserved for an attempt to create a variable with a direct-initializer of a value-initialized temporary: `A a(A());` (My mistake originally.) – CB Bailey Sep 28 '10 at 09:31
  • see also http://stackoverflow.com/questions/180172/default-constructor-with-empty-brackets – M.M Oct 21 '14 at 19:27

3 Answers3

34

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
  • 12,490
  • 3
  • 42
  • 53
  • 1
    +1, btw Visual C++ issues `warning C4930: prototyped function not called (was a variable definition intended?)` in such cases. – sharptooth Sep 28 '10 at 07:44
  • 1
    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 Oct 21 '10 at 00:30
  • @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 Oct 21 '10 at 16:18
18

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
  • 91,295
  • 49
  • 239
  • 345
1

You can use it like this:

Class obj;
//or
Class *obj = new Class(/*constructor arguments*/);
Hitman_99
  • 2,252
  • 2
  • 19
  • 21