Cpp - class Member Functions

Introduction

Every class member function that you declare must be defined.

A member function definition begins with the name of the class followed by the scope resolution operator :: and the name of the function.

const Member Functions

Constant member function won't change the value of any members of the class.

To declare a function as constant, put the keyword const after the parentheses:

void displayPage() const; 
int getSpeed() const; 

If you declare a function as const and the function changes the value of class members, the compiler will flag it as an error.

Here's an example:

class Cart 
{ 
public: 
    int speed; 
    int wheelSize; 
    pedal(); 
    brake(); 
}; 


void Cart::pedal() 
{ 
    std::cout << "Pedaling\n"; 
} 

Class functions have the same capabilities as functions; they can have parameters and return a value.

The following code defines a Cart class.

Demo

#include <iostream> 
 
class Cart //from   ww w  .  j  av a2s.  c o  m
{ 
public: 
    int getSpeed(); 
    void setSpeed(int speed); 
    void pedal(); 
    void brake(); 
private: 
    int speed; 
}; 

// get the trike's speed 
int Cart::getSpeed() 
{ 
    return speed; 
} 

// set the trike's speed 
void Cart::setSpeed(int newSpeed) 
{ 
    if (newSpeed >= 0) 
    { 
        speed = newSpeed; 
    } 
} 

// pedal the trike 
void Cart::pedal() 
{ 
    setSpeed(speed + 1); 
    std::cout << "\nPedaling; tricycle speed " << speed << " mph\n"; 
} 
 
// apply the brake on the trike 
void Cart::brake() 
{ 
    setSpeed(speed - 1); 
    std::cout << "\nBraking; tricycle speed " << speed << " mph\n"; 
} 

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

Result

Related Topics