Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the difference between the two copy constructor invocation in C++?

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

like image 884
J.Doe Avatar asked Jun 28 '18 03:06

J.Doe


People also ask

What is difference between copy constructor and constructor?

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.

What is the difference between invoking a copy constructor and using an assignment?

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.

What is a copy constructor 2?

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.


1 Answers

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.

like image 180
songyuanyao Avatar answered Nov 15 '22 13:11

songyuanyao