Custom Copy Constructors and Assignment Operators - C++ Class

C++ examples for Class:Constructor

Description

Custom Copy Constructors and Assignment Operators

Demo Code

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

using namespace std;

class Car// w w w.ja  v  a  2s.  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) = default;
    Car& operator=(const Car& other) = default;

    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