Post

Function Overloading vs Overriding in C++

Function Overloading vs Overriding in C++

Function Overloading vs Overriding in C++


Prerequisites


1. What are Overloading and Overriding

C++ supports two important polymorphism concepts:

  • Overloading → Same function name, different parameters
  • Overriding → Same function signature, different implementation (inheritance)
FeatureOverloadingOverriding
ScopeSame classInheritance
Function nameSameSame
ParametersDifferentSame
BindingCompile-timeRuntime
KeywordNonevirtual, override

2. Overloading

Multiple functions with the same name but different parameter lists

✔ Example
1
2
3
4
5
6
7
8
9
int add(int a, int b) 
{
    return a + b;
}

double add(double a, double b) 
{
    return a + b;
}

Same name add, different parameter types

  • Happens at compile-time (static polymorphism)
  • Based on:
    • Number of parameters
    • Type of parameters
  • Return type alone is NOT enough
❌ Invalid Overloading
1
2
int foo(int a);
double foo(int a);  // ❌ error
  • Resolved at compile-time → fast

3. Overriding

Derived class provides a new implementation of a base class virtual function

✔ Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Base 
{
public:
    virtual void print()
    {
        std::cout << "Base\n";
    }
};

class Derived : public Base 
{
public:
    void print() override 
    {
        std::cout << "Derived\n";
    }
};
✔ Usage
1
2
Base* obj = new Derived();
obj->print();  // Output: Derived

Runtime polymorphism

  • Requires virtual function
  • Happens at runtime
  • Uses vtable (virtual table)
  • Uses vtable lookup → small runtime cost
This post is licensed under CC BY 4.0 by the author.