InterviewSolution
Saved Bookmarks
| 1. |
Explain copy constructor vs assignment operator in C++. |
|
Answer» A copy CONSTRUCTOR is a member function that uses another object of the same class to initialise an object. Assignment operators are used to giving a variable a value. The assignment operator's left side OPERAND is a variable, while the assignment operator's right side operand is a value. // C++#include<iostream> #include<stdio.h> using namespace STD; class IB{ public: IB() {} IB(const IB &b) { cout<<"Copy constructor is called "<<endl; } IB& operator = (const IB &b) { cout<<"Assignment operator is called "<<endl; return *this; } }; // Driver codeint main() { IB b1, b2; b2 = b1; IB b3 = b1; getchar(); return 0; }Output: Assignment operator is calledCopy constructor is calledWhen a new object is GENERATED from an existing object as a copy of the old object, the copy constructor is called. When an already initialised object is given a new value from another object, the assignment operator is used. |
|