Tuesday, September 13, 2011

Copy Constructor

A copy constructor is one that takes a single argument of the same type as the class, passed by reference. Such that you can copy member variable from another object of the same class.

example:
Copy Constructor

#include <iostream>

using namespace std;

class MyClass{
public:
MyClass();
MyClass(string note, const string mName = "DEFAULT_NAME");
MyClass(MyClass& src); //Copy Constructor
~MyClass();
private:
string myName;
string myNote;
};

MyClass::MyClass(){
myName = "default constructor without argument";
myNote = "";
cout << "MyClass Constructor: " << myName << endl;

}

//Copy Constructor
MyClass::MyClass(MyClass& src){
myName = src.myName;
myNote = src.myNote;
cout << "Copy Constructor: " << myName << " : " << myNote << endl;
}

MyClass::MyClass(string note, const string mName){
myName = mName;
myNote = note;
cout << "MyClass Constructor: " << myName << " : " << myNote << endl;
}


MyClass::~MyClass(){
cout << "MyClass Destructor: " << myName << endl;
}

int main()
{
MyClass myClass1;
MyClass myClass2("Using default Name");
MyClass myClass3("with name", "MyClass 3");
MyClass copyClass(myClass3);
return 0;
}




Related Post:
- Compiler auto-generated Copy Constructor


No comments:

Post a Comment