fbpx

C++ source code demo of copy constructor, default constructor, and assignment operator

(Last Updated On: June 20, 2010)

Another example of Copy Constructor, Default Constructor, Assignment Operator with CONVERSION OPERATOR

#include
using namespace std;

class A {
string s;
public:
A(string str) {s=str;} //constructors must be public
A(A&){} //copy ctr and also does deep copy
A(int iname): x(iname) {}
//int i2=2; // note that you cannot initialize non-const static members in classes
int x;
double d;
operator int() {return x;} //this is a conversion operator

// below is the copy assignment operator,also passed & allows chaining like a=b=c;
// this also demonstrates deep/hard copy
A & operator = (const A & rhs) {
//delete this; this causes program crash
if (this != &rhs) {
//*this = other; // this line can program crash
x=rhs.x;
d=rhs.d;
}
//by convention always return * this
return *this;
}
A() {} //this default ctr is needed because of the 1 argument constructor and has to be public
};

int main() {
string str=”hello”;
A a1;
a1.x=1;
a1.d=2;
A b=a1; //this calls copy ctr
A b2(a1); //this calls copy ctr
b.x=2;
A *c=new A(a1);
c->x=2;
A* d1=new A(a1); //note A* d[10]=new A(a1); causes error

A* d2[10];
for(int i=0;i<10;++i) d2[i]=new A; int i=A(10); //this uses conversion operator (type int) A d3; d3=a1; //this uses copy assignment operator cout<<"d3.x="<FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

Subscribe For Latest Updates

Sign up to best of business news, informed analysis and opinions on what matters to you.
Invalid email address
We promise not to spam you. You can unsubscribe at any time.

NOTE!

Check NEW site on stock forex and ETF analysis and automation

Scroll to Top