Implicit and Default Copy Constructors and Assignment Operators - C++ Class

C++ examples for Class:Constructor

Description

Implicit and Default Copy Constructors and Assignment Operators

#include <cinttypes>
#include <iostream>
#include <string>

using namespace std;

class Car
{
private:
    string m_Name;
    int m_NumberOfWheels{};

public:
    Car() = default;

    Car(string name, int numberOfWheels)
        : m_Name{ name }
        , m_NumberOfWheels{ numberOfWheels }
    {

    }

    ~Car()
    {
        cout << m_Name << " at " << this << " is being destroyed!" << endl;
    }

    int GetNumberOfWheels()
    {
        return m_NumberOfWheels;
    }
};

int main(int argc, char* argv[])
{
    Car myCar{ "myCar", 4 };
    cout << "Number of wheels: " << myCar.GetNumberOfWheels() << endl;

    Car myMotorcycle{ "myMotorcycle", 2 };
    cout << "Number of wheels: " << myMotorcycle.GetNumberOfWheels() << endl;

    Car myCopiedCar{ myCar };
    cout << "Number of wheels: " << myCopiedCar.GetNumberOfWheels() << endl;

    Car mySecondCopy;
    mySecondCopy = myCopiedCar;
    cout << "Number of wheels: " << mySecondCopy.GetNumberOfWheels() << endl;

    return 0;
}

Related Tutorials