Performing a byte-by-byte (shallow) copy is not correct when the class holds assets - C++ Class

C++ examples for Class:object

Description

Performing a byte-by-byte (shallow) copy is not correct when the class holds assets

Demo Code

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

class Person/* w  ww.j  av  a  2  s  .c  om*/
{
  public:
    Person(const char *pN)
    {
        cout << "Constructing " << pN << endl;
        pName = new string(pN);
    }
    ~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