Cpp - Organizing Class Declarations and Function Definitions

Introduction

Class definitions often are kept separate from their implementations in the source code of C++ programs.

Each function that you declare for your class must have a definition.

The definition files normally end with .cpp.

The declaration in a header file with the same name ending with the file extension .hpp.

If you put the declaration of the Cart class in a file named Cart.hpp, the definition of the class functions would be in Cart.cpp.

The header file can be incorporated into the .cpp file with a preprocessor directive:

#include "Cart.hpp" 

Inline Implementation

You can make member functions inline. The keyword inline appears before the return value, as in this example:

inline int Cart::getSpeed() 
{ 
    return speed; 
} 

You can put the definition of a function in the declaration of the class, which automatically makes that function inline. Here's an example:

class Cart 
{ 
public: 
    int getSpeed() const { return speed; } 
    void setSpeed(int newSpeed); 
}; 

Demo

#include <iostream> 
 
class Cart //from w w w  .  j  a  v  a 2  s . c  om
{ 
public: 
    Cart(int initialSpeed); 
    ~Cart(); 
    int getSpeed() const { return speed; } 
    void setSpeed(int speed); 
    void pedal() 
    { 
          setSpeed(speed + 1); 
          std::cout << "Pedaling " << getSpeed() << " mph\n\n"; 
    } 
    void brake() 
    { 
          setSpeed(speed - 1); 
           std::cout << "Pedaling " << getSpeed() << " mph\n"; 
    } 
private: 
    int speed; 
};  
// constructor for the object 
Cart::Cart(int initialSpeed) 
{ 
    setSpeed(initialSpeed); 
} 
 
// destructor for the object 
Cart::~Cart() 
{ 
    // do nothing 
} 
 
// set the trike's speed 
void Cart::setSpeed(int newSpeed) 
{ 
    if (newSpeed >= 0) 
        speed = newSpeed; 
} 
 
// create a trike and ride it 
int main() 
{ 
    Cart shoppingCart(5); 
    shoppingCart.pedal(); 
    shoppingCart.pedal(); 
    shoppingCart.brake(); 
    shoppingCart.brake(); 
    shoppingCart.brake(); 
    return 0; 
}

Result

Related Topic