Suppose I have a class called Person and the constructor is
Person(int age)
{
m_age = age;
}
When declaring a Person and initializing it, is there a difference between:
Person john(36);
and
Person john = Person(36);
Suppose I have a class called Person and the constructor is
Person(int age)
{
m_age = age;
}
When declaring a Person and initializing it, is there a difference between:
Person john(36);
and
Person john = Person(36);
The first one is direct initialization while the latter copy initialization. They're two different semantics but in general:
direct initialization works by overload resolution on the constructors: it will find the best matching constructor and perform every implicit conversion sequence needed
copy initialization uses copy/move semantics from a temporary object. In case the objects aren't the same an implicit conversion sequence will be set up (in this regard it is less flexible than direct initialization)
Notice that compilers are allowed (cfr. copy elision/RVO) by the standard to elide the temporary creation completely.
Also related: Is there a difference in C++ between copy initialization and direct initialization?
The difference is that the code:-
Person john(36);
first creates an object john calls the parameterized constructor and assigns the value 36 to the variable m_age.
While the code:-
Person john = Person(36);
first creates a temporary object, assigns it's variable the value 36 and then creates the object john and further calls the copy constructor to copy the value of the variable m_age.
The first method is more time efficient however second method provides a flexibility of usage as we can define our own copy constructor and alter the way value is being copied.