Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the copy constructor being used instead of the assignment operator

Tags:

c++

This is how MyClass is defined:

class MyClass {
    double x, y;
    public:
        MyClass (double a = 0., double b = 0.) {
            x = a;
            y = b;
            cout << "Using the default constructor" << endl;
        }
        MyClass (const MyClass& p) {
            x = p.x;
            y = p.y;
            cout << "Using the copy constructor" << endl;
        }
        MyClass operator =(const MyClass& p) {
            x = p.x;
            y = p.y;
            cout << "Using the assignment operator" << endl;
            return *this;
        }
};

And I tested when each constructor or method is called in my main program:

int main() {
    cout << "MyClass p" << endl; MyClass p; cout << endl;
    cout << "MyClass r(3.4)" << endl; MyClass r(3.4); cout << endl;
    cout << "MyClass s(r)" << endl; MyClass s(r); cout << endl;
    cout << "MyClass u = s" << endl; MyClass u = s; cout << endl;
    cout << "s = p" << endl; s = p; cout << endl;
}

Why is the copy constructor being used in the fourth example, MyClass u = s, instead of the assignment operator?

EDIT

Including the output, as asked:

MyClass p
Using the default constructor

MyClass r(3.4)
Using the default constructor

MyClass s(r)
Using the copy constructor

MyClass u = s
Using the copy constructor

s = p
Using the assignment operator
Using the copy constructor
like image 950
dabadaba Avatar asked Dec 19 '22 16:12

dabadaba


2 Answers

Because is not an actual assignment since you declare u at the same time. Thus, the constructor is called instead of the assignment operator. And this is more efficient because if it wasn't for this feature there would have been the redundancy of calling first a default constructor and then the assignment operator. This would have evoked the creation of unwanted copies and thus would had deteriorate the performance of the C++ model significantly.

like image 188
101010 Avatar answered Feb 16 '23 03:02

101010


Because that's the declaration and initialization of a variable, not the assigment of a value to an existing variable. In the context of a variable declaration, = is just syntactic sugar for passing a parameter to the ctor.

like image 23
Manu343726 Avatar answered Feb 16 '23 02:02

Manu343726