.Line 4 is also using the copy constructor to copy over all the member variables from s1 into s2
No. Line 4 is invoking copy-assignment operator, not the copy-constructor.
A constructor is invoked when an object is being initialized in its declaration. Line 4 doesn't declare anything, so it invokes copy-assignment which is operator=
. Even if the class doesn't overload operator=
, the compiler will generate one for you, and then it will be invoked. So in any case, the line 4 cannot invoke copy-constructor.
Note that you can disable operator=
for your class if you think the copy-assignment of objects of your class doesn't make sense. To disable this, all you need to do is, declare the operator=
in the private section of your class, and then don't provide any definition for it. Something like this:
struct A
{
A(A const &) {} //copy through copy-constructor is allowed
private:
A& operator=(A const &);//copy through copy-assignment is disallowed
};
A x
A y(x); //ok - copy-constructor is allowed
y = x; //error - copy-assignment is disallowed
Likewise, you can disable both : copy-constructor and copy-assignment. For example, the standard library has disabled copy-semantics for all stream classes.
In C++11, you can disable copy-semantic explicitly as:
struct B
{
private:
B(B const &) = delete;
B& operator=(B const &) = delete;
};
Copy-semantic is disabled for class B
, and the usage of =delete
makes it explicit. It also increases the readability of the code and reveals the programmer's intention clearly.