C++ Constructor deep copy

Description

C++ Constructor deep copy

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

class Person/*from ww w .j a  va 2s. c om*/
{
  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;
}



PreviousNext

Related