Cpp - Overloading Versus Overriding

Introduction

When you overload a member function, you create more than one function with the same name but with different signatures.

When you override a member function, you create a function in a derived class with the same name as a function in the base class and with the same signature.

Hiding the Base Class Member Function

Demo

#include <iostream> 
   //from  w  ww . j  av a2  s . c  o  m
class Mammal 
{ 
public: 
    void move() const { std::cout << "Mammal moves one step\n"; } 
    void move(int distance) const  
           { std::cout << "Mammal moves " << distance <<" steps\n"; } 
protected: 
    int age; 
    int weight; 
}; 
   
class Dog : public Mammal 
{ 
public: 
    void move() const { std::cout << "Dog moves 5 steps\n"; } 
}; // you may receive a warning that you are hiding a function! 
   
int main() 
{ 
    Mammal bigAnimal; 
    Dog fido; 
    bigAnimal.move(); 
    bigAnimal.move(2); 
    fido.move(); 
    return 0; 
}

Result

Mammal class declares the two overloaded move() functions.

Dog overrides the version of move() with no parameters.

Related Topic