#include <iostream>This example shows a class SomeData containing an int pointer member pd. A copy constructor is provided to create a new instance of this pointer and then copy the original value into it. The id member is provided by the normal constructor but is just set to a nominal value in the copy constructor.
#include <string>
using namespace std;
struct SomeData {
int * pd;
string id;
SomeData(SomeData & ref) {
cout << "Copy Constructor called" << endl;
pd = new int (*ref.pd) ;
id = "Copy Constructed";
}
SomeData(string name) {
pd = new int(0) ;
id=name;
cout << "Constructor for " << id << endl;
};
~SomeData() {
cout << "Destructor for " << id << endl;
delete pd;
}
};
int main() {
SomeData s("First") ;
*s.pd =9;
SomeData s2=s;
cout << *s2.pd << endl;
return 0;
}
If you comment out the copy constructor, it will still compile but when run will copy the pointer and end up freeing the same pointer twice likely causing an exception.
As we have allocated memory in the various constructors, it is vital that the memory is released when the object is destroyed so don't forget the destructor in that case.
On the next page : Using Assignment Operators

