Declaring a Class - C++ Class

C++ examples for Class:Class Creation

Description

Declaring a Class

Demo Code

#include <iostream> 
 
class Bike //from  ww  w  .  j  a  v  a  2  s.  c  om
{ 
public: 
    int getSpeed(); 
    void setSpeed(int speed); 
    void pedal(); 
    void brake(); 
private: 
    int speed; 
}; 

// 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; Bike speed " << speed << " mph\n"; 
} 
 
// apply the brake on the trike 
void Bike::brake() 
{ 
    setSpeed(speed - 1); 
    std::cout << "\nBraking; tricycle speed " << speed << " mph\n"; 
} 

// create a trike and ride it 
int main() 
{ 
    Bike my; 
    my.setSpeed(0); 
    my.pedal(); 
    my.pedal(); 
    my.brake(); 
    my.brake(); 
    my.brake(); 
    return 0; 
}

Result


Related Tutorials