Look at the following codes:
class Foo
{
public:
Foo(){}
explicit Foo(const Foo &){}
};
int main()
{
Foo foo1;
Foo foo2(foo1);
Foo foo3 = foo1; //can not compile
return 0;
}
Why Foo foo3 = foo1;
can not compile, and what's the difference between the two copy constructor invocation?
ps: My compiler tools is GCC4.8.2
Constructor: It is a method which has the same name as the class which is used to create an instance of the class. Copy Constructor: Used to create an object by copying variables from another object of the same class.
Copy Constructor is invoked when a new object is initialized with old object and also invoked when the object is passed to a function as non-reference parameter. Assignment operator is invoked when the value of an old object is assigned to a new object.
t2 = t1; // -----> (2) A copy constructor is called when a new object is created from an existing object, as a copy of the existing object. The assignment operator is called when an already initialized object is assigned a new value from another existing object.
Foo foo2(foo1);
is direct initialization. Foo foo3 = foo1;
is copy initialization. The difference between them is
Copy-initialization is less permissive than direct-initialization: explicit constructors are not converting constructors and are not considered for copy-initialization.
The copy constructor of Foo
is declared as explicit
, which is not considered in copy initialization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With