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
  • 505,946
  • 29
  • 409
  • 696
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,952
  • 4
  • 29
  • 44
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
  • 134,614
  • 21
  • 188
  • 335