Cpp - Overload assignment operator =

Introduction

The following code overloads a custom assignment operator.

Demo

#include <iostream> 
   //from   w ww .j  a v  a 2  s. c o m
class Cart 
{ 
public: 
    Cart();  
    // copy constructor and destructor use default 
    int getSpeed() const { return *speed; } 
    void setSpeed(int newSpeed) { *speed = newSpeed; } 
    Cart operator=(const Cart&); 
   
private: 
    int *speed; 
}; 
   
Cart::Cart() 
{ 
    speed = new int; 
    *speed = 5; 
} 
   
Cart Cart::operator=(const Cart& rhs) 
{ 
    if (this == &rhs) 
           return *this; 
    delete speed; 
    speed = new int; 
    *speed = rhs.getSpeed(); 
    return *this; 
} 
   
int main() 
{ 
    Cart shoppingCart; 
    std::cout << "speed: " << shoppingCart.getSpeed() << std::endl; 
    std::cout << "Setting Wichita's speed to 6 ..." << std::endl; 
    shoppingCart.setSpeed(6); 
    Cart your_cart; 
    std::cout << "Dallas' speed: " << your_cart.getSpeed() << std::endl; 
    std::cout << "Copying Wichita to Dallas ..." << std::endl; 
    shoppingCart = your_cart; 
    std::cout << "Dallas' speed: " << your_cart.getSpeed() << std::endl; 
    return 0; 
}

Result