Use a constructor to initialize the object - C++ Class

C++ examples for Class:Constructor

Description

Use a constructor to initialize the object

Demo Code

                                
#include <iostream> 
                                //from  w w  w .  j  a  v a 2 s  .co  m
class Bike 
{ 
public: 
    Bike(int initialAge); 
    ~Bike(); 
    int getSpeed(); 
    void setSpeed(int speed); 
    void pedal(); 
    void brake(); 
private: 
    int speed; 
}; 
                                  
// constructor for the object 
Bike::Bike(int initialSpeed) 
{ 
    setSpeed(initialSpeed); 
} 
                                  
// destructor for the object 
Bike::~Bike() 
{ 
} 
                                 
// get the trike's speed 
int Bike::getSpeed() 
{ 
    return speed; 
} 
                                   
// set the trike's speed 
void Bike::setSpeed(int newSpeed) 
{ 
    if (newSpeed >= 0) 
    { 
        speed = newSpeed; 
    } 
} 
                                   
// pedal the trike 
void Bike::pedal() 
{ 
    setSpeed(speed + 1); 
    std::cout << "\nPedaling; tricycle speed " << getSpeed() << " mph\n"; 
} 
                                 
// apply the brake on the trike 
void Bike::brake() 
{ 
    setSpeed(speed - 1); 
    std::cout << "\nBraking; tricycle speed " << getSpeed() << " mph\n"; 
} 
                                   
int main() { 
    Bike my(5); 
    my.pedal(); 
    my.pedal(); 
    my.brake(); 
    my.brake(); 
    my.brake(); 
    return 0; 
}

Result


Related Tutorials