Define a custom assignment operator and avoids the same-object problem. - C++ Class

C++ examples for Class:Operator Overload

Description

Define a custom assignment operator and avoids the same-object problem.

Demo Code

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

Result


Related Tutorials