c++ - Why is the copy constructor being used instead of the assignment operator -


this how myclass defined:

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

and tested when each constructor or method called in 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 copy constructor being used in fourth example, myclass u = s, instead of assignment operator?

edit

including output, asked:

myclass p using default constructor  myclass r(3.4) using default constructor  myclass s(r) using copy constructor  myclass u = s using copy constructor  s = p using assignment operator using copy constructor 

because not actual assignment since declare u @ same time. thus, constructor called instead of assignment operator. , more efficient because if wasn't feature there have been redundancy of calling first default constructor , assignment operator. have evoked creation of unwanted copies , had deteriorate performance of c++ model significantly.


Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -