Using the default copy constructor, creating a deep copy to copy the existing values into new memory. - C++ Class

C++ examples for Class:Constructor

Description

Using the default copy constructor, creating a deep copy to copy the existing values into new memory.

Demo Code

                                                                 
#include <iostream> 
                                                                    
class Bike /*from  www  .j  a  v  a 2s  .c  om*/
{ 
public: 
    Bike();                                 // default constructor 
    Bike(const Bike&);                 // copy constructor 
    ~Bike();                                // destructor 
    int getSpeed() const { return *speed; } 
    void setSpeed(int newSpeed) { *speed = newSpeed; } 
    void pedal(); 
    void brake(); 
                                                                    
private: 
    int *speed; 
}; 
                                                                    
Bike::Bike() 
{ 
    speed = new int; 
    *speed = 5; 
} 
                                                                    
Bike::Bike(const Bike& rhs) 
{ 
    speed = new int; 
    *speed = rhs.getSpeed(); 
} 
                                                                    
Bike::~Bike() 
{ 
    delete speed; 
    speed = NULL; 
} 
                                                                  
void Bike::pedal() 
{ 
    setSpeed(*speed + 1); 
    std::cout << "\nPedaling " << getSpeed() << " mph" << std::endl; 
} 
void Bike::brake() 
{  
    setSpeed(*speed - 1); 
    std::cout << "\nPedaling " << getSpeed() << " mph" << std::endl; 
} 
                                                                    
int main() 
{ 
    std::cout << "Creating trike named my ..."; 
    Bike my; 
    my.pedal(); 
    std::cout << "Creating trike named dallas ..." << std::endl; 
    Bike dallas(my); 
    std::cout << "my's speed: " << my.getSpeed() << std::endl; 
    std::cout << "dallas's speed: " << dallas.getSpeed() << std::endl; 
    std::cout << "setting my to 10 ..." << std::endl; 
    my.setSpeed(10); 
    std::cout << "my's speed: " << my.getSpeed() << std::endl; 
    std::cout << "dallas's speed: " << dallas.getSpeed() << std::endl; 
    return 0; 
}

Result


Related Tutorials