MockExams

Function Overloading, Inline Functions & Default Arguments

AI draft, not yet reviewedUnit 3: Functions in C++About 2 minutes

Idea in plain words

Inline Functions: Suggests that the compiler replace function calls with the exact body code, eliminating call overhead (stack pushing, jump, return). Suitable for short functions.

Exam tip

High-yield exam topic (High).

Explanation

Function overloading provides compile-time polymorphism. The C++ compiler disambiguates overloaded functions via name mangling, embedding parameter types directly into internal symbol table identifiers. Function inlining eliminates the runtime cost of calling small functions while preserving the clean abstraction of modular routines.

Key points

  • Default Arguments: Enables functions to be invoked without specifying all arguments; default parameters must appear trailing from right to left.
  • Function Overloading: Multiple functions sharing the same name but differing in parameter count, types, or ordering. Resolved at compile-time (Name Mangling).
  • Ambiguity in Overloading: Occurs when type promotion or default arguments make multiple overloaded candidates equally valid.

Example

Example

void display(char c = '*', int n = 10); Valid calls: display(); display('#'); display('$', 20). Invalid: cannot pass n without specifying c.

Code examples

// Function Overloading & Inline Functions in C++
#include <iostream>
using namespace std;

inline int square(int x) { return x * x; } // Expands in-place

// Overloaded functions
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c = 0) { return a + b + c; } // Default argument

int main() {
    cout << square(5) << endl;
    cout << add(10, 20) << endl;        // Calls add(int, int)
    cout << add(2.5, 3.5) << endl;      // Calls add(double, double)
    cout << add(10, 20, 30) << endl;    // Calls add(int, int, int)
    return 0;
}

Exam questions

  • [7 Marks] What is an inline function? What are its advantages and limitations? When will the compiler ignore the inline request?
  • [7 Marks] Explain function overloading with suitable C++ examples. State the conditions that lead to ambiguity in overloading.

BIT154CO

Switch Course

On this page

Past Exam Questions

Not asked in past exams yet

This topic hasn't appeared in previous exam papers.

Search BIT154CO

Reading

Theme
Reading mode
Text size
Default
Font
Line width
Line spacing