HimNG
HimNG

Reputation: 11

Constructor called with creating object

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?

Upvotes: 1

Views: 55

Answers (2)

M.M
M.M

Reputation: 141648

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.

Upvotes: 0

tinkertime
tinkertime

Reputation: 3042

Those two invocations are identical.

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

Upvotes: 3

Related Questions