Deep Copy for object - C++ Class

C++ examples for Class:Constructor

Description

Deep Copy for object

Demo Code

#include <cinttypes>
#include <cstring>
#include <iostream>

using namespace std;

class Car/*from  w  w  w.  jav  a2s  . c o m*/
{
private:
    char* m_Name{};
    int m_NumberOfWheels{};

public:
    Car() = default;

    Car(const char* name, int numberOfWheels)
        : m_NumberOfWheels{ numberOfWheels }
    {
        const int length = strlen(name) + 1; // Add space for null terminator
        m_Name = new char[length]{};
        strcpy(m_Name, name);
    }

    ~Car()
    {
        delete m_Name;
        m_Name = nullptr;
    }

    Car(const Car& other)
    {
        const int length = strlen(other.m_Name) + 1; // Add space for null terminator
        m_Name = new char[length]{};
        strcpy(m_Name, other.m_Name);

        m_NumberOfWheels = other.m_NumberOfWheels;
    }

    Car& operator=(const Car& other)
    {
        if (m_Name != nullptr)
        {
            delete m_Name;
        }
        const int length = strlen(other.m_Name) + 1; // Add space for null terminator
        m_Name = new char[length]{};
        strcpy(m_Name, other.m_Name);

        m_NumberOfWheels = other.m_NumberOfWheels;

        return *this;
    }

    char* GetName()
    {
        return m_Name;
    }

    int GetNumberOfWheels()
    {
        return m_NumberOfWheels;
    }
};

int main(int argc, char* argv[])
{
    Car myAssignedCar;

    {
        Car myCar{ "myCar", 4 };
        cout << "Car name: " << myCar.GetName() << endl;

        myAssignedCar = myCar;
        cout << "Car name: " << myAssignedCar.GetName() << endl;
    }

    cout << "Car name: " << myAssignedCar.GetName() << endl;

    return 0;
}

Result


Related Tutorials