Tuesday, September 13, 2011

Compiler auto-generated Copy Constructor

If you don’t write your own copy constructor, the compiler generate a defaut one for you, to copy member variables one-by-one.

example:
Compiler auto-generated Copy Constructor

#include <iostream>

using namespace std;

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

MyClass::MyClass(){
myName = "default constructor without argument";
myNote = "";
cout << "MyClass Constructor: " << myName << 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;
}



No comments:

Post a Comment