1
class P{
    public:
    P(int x,int y) { cout << "constructor called" << endl;}
};

int main ()
{
    P(5,4);    // constructor called  
    P p(5,4);  // constructor called
    return 0;
}

What is the difference between the above two constructor calls?

How does P(5,4) call the constructor?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
HimNG
  • 11
  • 3

2 Answers2

3

Those two invocations are identical.

The only difference is in the second you hold the created object in a local variable p

tinkertime
  • 2,972
  • 4
  • 30
  • 45
0

In C++ a type name followed by a (possibly empty) parenthesized list is a prvalue expression that (usually) results in creation of a temporary object of that type, and the list consists of the arguments to the constructor.

An exception to this is when there is syntactic ambiguity, see here.

Compare with P p = P(5,4); In P(5,4); you still have the same righthand side, but you just let the object be created and destroyed instead of associating it with a name p.

M.M
  • 138,810
  • 21
  • 208
  • 365