Different ways of constructing a object using another object

109 Views Asked by At

A few days ago I read this article: Constructor of type int

But I think I have to clarify something first.

Suppose I have a class Myclass and I already created an object obj1.

Are there differences between writing:

Myclass obj2(obj1);

and

Myclass obj2 = obj1;

?

Like this article said: What happens when a new object is created using another (existing) object?.

Is there a temporary object created to be assigned to the newly created object? Is the copy constructor invoked to create that temporary object? Then the newly created object is constructed by what?

I am confused.

I think this question must have been asked before. But I just couldn't find one using the keywords I can come up with.

1

There are 1 best solutions below

0
Some programmer dude On

From a strict point of view,

Myclass obj2(obj1);

will be a direct initialization.

While

Myclass obj2 = obj1;

will be a copy initialization.

However, the effect of both will be the exact same: The Myclass copy-constructor being invoked.