Creating a deep copy by copying each member in the class - C++ Class

C++ examples for Class:object

Description

Creating a deep copy by copying each member in the class

Demo Code

#include <string>
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

class Person//w w  w .ja  v a  2 s  .c  o  m
{
  public:
    Person(const char *pN)
    {
        cout << "Constructing " << pN << endl;
        pName = new string(pN);
    }
    Person(Person& person)
    {
        cout << "Copying " << *(person.pName) << endl;
        pName = new string(*person.pName);
    }
    ~Person()
    {
        cout << "Destructing " << pName << " (" << *pName << ")" << endl;
        *pName = "already destructed memory";
    }
 protected:
    string *pName;
};

void fn()
{
    Person p1("Mary");
    Person p2(p1);
}

int main(int argcs, char* pArgs[])
{
    cout << "Calling fn()" << endl;
    fn();
    cout << "Back in main()" << endl;
    return 0;
}

Result


Related Tutorials