SyntaxPilot
Courses/C++/Lesson 7
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

C++ · Lesson 7 of 40

Functions and overloading

queued

These are the notes for C++ episode 7. Loops (episode 6) repeat work in one place. Here the same job is needed in many places, and copy-paste lets a bug slip through. You will invent the function: define it once, call it by name. Then parameters and arguments, return values, void, the famous was not declared in this scope error and prototypes, pass by value (why a function can't change your variable), local scope, default arguments, and function overloading (one name, many jobs) with its ambiguous call trap. Every example below was compiled with g++ -O2 -std=c++17 main.cpp -o main (g++ 13.3, the same command as the SyntaxPilot compiler) and run; the outputs and error messages are copied from those runs.

The problem: Meena's tiffin service and the copy-paste bug

Meena runs a tiffin service. Her son wrote a program that prints each customer's bill with 5% GST. Three customers, so the same GST line appears three times:

#include <iostream>
using namespace std;

int main() {
    double a = 120 * 1.05;
    cout << "Ravi pays: " << a << endl;
    double b = 80 * 1.05;
    cout << "Priya pays: " << b << endl;
    double c = 150 * 1.05;
    cout << "Arjun pays: " << c << endl;
    return 0;
}

Output:

Ravi pays: 126
Priya pays: 84
Arjun pays: 157.5

Then GST goes up to 12%. He changes lines 5 and 7 to 1.12, but misses line 9:

Ravi pays: 134.4
Priya pays: 89.6
Arjun pays: 157.5

No error, no warning, just a wrong bill for Arjun. Why it failed: the same rule lived in three places, so there were three chances to forget one. We need to write the rule once and use it everywhere.

The fix: a function (the sugarcane juice machine)

At a juice stall In C++ Name
The machine is built once, then used all day double withGst(double price) { ... } function definition
"One glass, please!" (press the button) withGst(120) function call
Cane goes in price receives 120 parameter (input)
Juice comes out return price * 1.12; return value (output)

A function is a named block of code that does one job. You define it once and call it by its name, with round brackets, as many times as you like.

#include <iostream>
using namespace std;

double withGst(double price) {
    return price * 1.12;
}

int main() {
    cout << "Ravi pays: " << withGst(120) << endl;
    cout << "Priya pays: " << withGst(80) << endl;
    cout << "Arjun pays: " << withGst(150) << endl;
    return 0;
}

Output:

Ravi pays: 134.4
Priya pays: 89.6
Arjun pays: 168

All three bills are right, because there is only one rule, on line 5. If GST changes again, you change one number.

Anatomy of a function

double    withGst   (double price)   { return price * 1.12; }
  │          │            │                    │
return type  name     parameter list          body
  • Return type (double): the kind of value the function hands back.
  • Name (withGst): how you call it. Same naming rules as variables.
  • Parameter list ((double price)): the inputs; each parameter is a variable that receives a value from the call.
  • Body ({ ... }): the code that runs.
  • return: sends the answer back to the caller and ends the function immediately.

What happens during a call

  1. main reaches withGst(120) and pauses.
  2. The value 120 is copied into the parameter price.
  3. The body runs; return price * 1.12; sends 134.4 back.
  4. main continues exactly where it paused, using 134.4 in place of the call.

Parameter vs argument: the parameter is the variable in the definition (price); the argument is the actual value in the call (120).

Two parameters, and "too few arguments"

Meena charges per day, so the bill needs two inputs. Think of a post-office form with two boxes: Days ___ Price ___. Each box is a parameter; what you write in them are the arguments, filled in order.

#include <iostream>
using namespace std;

double bill(int days, double price) {
    return days * price * 1.12;
}

int main() {
    cout << "Ravi: " << bill(20, 60) << endl;
    cout << "Priya: " << bill(22, 75) << endl;
    return 0;
}

Output:

Ravi: 1344
Priya: 1848

Parameters are separated by commas, and each one needs its own type (int days, double price, never int days, price). Leave a box empty, and the "clerk" refuses. Adding cout << "Arjun: " << bill(5) << endl; gives:

main.cpp: In function 'int main()':
main.cpp:11:30: error: too few arguments to function 'double bill(int, double)'
   11 |     cout << "Arjun: " << bill(5) << endl;
      |                          ~~~~^~~
main.cpp:4:8: note: declared here
    4 | double bill(int days, double price) {
      |        ^~~~

g++ even points at the declaration it compared your call against.

void functions: the doorbell

A juice machine hands you a glass; a doorbell rings and gives nothing back. A function that returns nothing has the return type void ("empty").

#include <iostream>
using namespace std;

void line() {
    cout << "--------------------" << endl;
}

int main() {
    line();
    cout << "Meena's Tiffins" << endl;
    line();
    return 0;
}

Output:

--------------------
Meena's Tiffins
--------------------
  • Empty brackets () mean the function takes no input, but you still need them in the call: line();.
  • A void function needs no return; it ends at its closing brace. (You may write return; with no value to leave early.)

Trying to use a void result, int x = line();:

main.cpp: In function 'int main()':
main.cpp:9:17: error: void value not ignored as it ought to be
    9 |     int x = line();
      |             ~~~~^~

In plain words: line() gives back nothing, so there is nothing to store in x. You can't take a glass from a doorbell.

Declare before use: prototypes

Many people like main at the top and the functions below it:

#include <iostream>
using namespace std;

int main() {
    cout << "Ravi pays: " << withGst(120) << endl;
    return 0;
}

double withGst(double price) {
    return price * 1.12;
}
main.cpp: In function 'int main()':
main.cpp:5:30: error: 'withGst' was not declared in this scope
    5 |     cout << "Ravi pays: " << withGst(120) << endl;
      |                              ^~~~~~~

The compiler reads the file top to bottom. At line 5 it has never heard of withGst, like dialling a name that isn't saved in your phone: no such contact. The fix is to "save the contact first" with a prototype (also called a declaration): the function's first line, ending in a semicolon, with no body.

#include <iostream>
using namespace std;

double withGst(double price);

int main() {
    cout << "Ravi pays: " << withGst(120) << endl;
    return 0;
}

double withGst(double price) {
    return price * 1.12;
}

Output: Ravi pays: 134.4.

What it is Example
Declaration (prototype) Announces name, parameter types and return type double withGst(double price);
Definition The declaration plus the body double withGst(double price) { return price * 1.12; }

In a prototype the parameter names are optional (double withGst(double); also works), but keeping them documents the meaning. You also can't define a function inside another function: putting withGst inside main gives error: a function-definition is not allowed here before '{' token.

Pass by value: the photocopy

A school gives 5 grace marks:

#include <iostream>
using namespace std;

void addBonus(int marks) {
    marks = marks + 5;
    cout << "Inside: " << marks << endl;
}

int main() {
    int marks = 78;
    addBonus(marks);
    cout << "In main: " << marks << endl;
    return 0;
}

Output:

Inside: 83
In main: 78

The bonus vanished. This is pass by value: the argument's value is copied into the parameter. It is like handing the clerk a photocopy of your form: whatever he writes on the copy, your original is untouched. The marks in addBonus and the marks in main are two different variables that happen to share a name.

Fix 1: return the new value and store it.

#include <iostream>
using namespace std;

int addBonus(int marks) {
    return marks + 5;
}

int main() {
    int marks = 78;
    marks = addBonus(marks);
    cout << "In main: " << marks << endl;
    return 0;
}

Output: In main: 83.

Sneak peek, fix 2: a reference. Write int& marks in the parameter (void addBonus(int& marks)) and the function works on the original instead of a copy. Output: Inside: 83 and In main: 83. References are covered properly in episode 10. For now: by default, functions get copies.

Local scope: the cook's notes stay in the kitchen

#include <iostream>
using namespace std;

double bill(int days, double price) {
    double total = days * price;
    return total * 1.12;
}

int main() {
    cout << bill(20, 60) << endl;
    cout << total << endl;
    return 0;
}
main.cpp: In function 'int main()':
main.cpp:11:13: error: 'total' was not declared in this scope
   11 |     cout << total << endl;
      |             ^~~~~
At a restaurant In C++
The cook scribbles total = 1200 on a kitchen notepad double total = ...; is a local variable
You only get the plate only the return value leaves the function
You can't see his notepad from the dining hall total is not visible in main

The scope of a name is the part of the code where it can be used. A local variable exists only inside its function's braces, from its declaration until the function returns. Parameters are local too. This is good: two functions can each have their own total without clashing.

Default arguments: "one chai" means regular

At a chai stall, "one chai" means the regular, unless you ask otherwise. Most of Meena's customers take the ₹60 tiffin, so give price a default argument: the value used when the caller doesn't pass one.

#include <iostream>
using namespace std;

double bill(int days, double price = 60) {
    return days * price * 1.12;
}

int main() {
    cout << "Ravi: " << bill(20) << endl;
    cout << "Priya: " << bill(22, 75) << endl;
    cout << "Arjun: " << bill(5) << endl;
    return 0;
}

Output:

Ravi: 1344
Priya: 1848
Arjun: 336

Arjun's bill(5) used the default 60 (5 × 60 × 1.12 = 336); Priya's 75 replaced it.

Defaults go last. Once a parameter has a default, every parameter after it needs one too. double bill(double price = 60, int days):

main.cpp:4:36: error: default argument missing for parameter 2 of 'double bill(double, int)'
    4 | double bill(double price = 60, int days) {
      |                                ~~~~^~~~
main.cpp:4:20: note: ...following parameter 1 which has a default argument
    4 | double bill(double price = 60, int days) {
      |             ~~~~~~~^~~~~~~~~~

Why: arguments fill parameters from the left, so in bill(20) the 20 would go into price, and days would be empty. (If you use a prototype, put the default in the prototype only, not in both.)

Function overloading: one name, many jobs

Painting the kitchen needs areas. Without overloading, every case needs a new name:

#include <iostream>
using namespace std;

int areaSquare(int side) { return side * side; }
int areaRect(int l, int w) { return l * w; }

int main() {
    cout << areaSquare(5) << endl;
    cout << areaRect(4, 6) << endl;
    return 0;
}

Output: 25 and 24. It works, but think of a chat app's Send button: one button sends a text, a photo or a location, depending on what you give it. In C++, several functions can share a name if their parameter lists differ. That is function overloading.

#include <iostream>
using namespace std;

int area(int side) { return side * side; }
int area(int l, int w) { return l * w; }
double area(double l, double w) { return l * w; }

int main() {
    cout << area(5) << endl;
    cout << area(4, 6) << endl;
    cout << area(4.5, 2.5) << endl;
    return 0;
}

Output:

25
24
11.25

The compiler picks a version from the arguments: how many there are and what types they have. This choice happens at compile time and is called overload resolution.

The ambiguous call

A wall 4 m by 2.5 m: area(4, 2.5) (one int, one double):

main.cpp: In function 'int main()':
main.cpp:11:17: error: call of overloaded 'area(int, double)' is ambiguous
   11 |     cout << area(4, 2.5) << endl;
      |             ~~~~^~~~~~~~
main.cpp:5:5: note: candidate: 'int area(int, int)'
    5 | int area(int l, int w) { return l * w; }
      |     ^~~~
main.cpp:6:8: note: candidate: 'double area(double, double)'
    6 | double area(double l, double w) { return l * w; }
      |        ^~~~

Ambiguous means "could mean more than one thing": converting 2.5 to int or 4 to double are equally good, so g++ refuses to guess. Fix: make the types exact, area(4.0, 2.5), which prints 10.

Overloading rules

Allowed? Example Why
Yes: different number of parameters area(int) and area(int, int) the call shows how many arguments
Yes: different parameter types area(int, int) and area(double, double) the call shows the types
No: only the return type differs int area(int) and double area(int) a call area(5) looks identical

The last one, verified:

main.cpp:5:8: error: ambiguating new declaration of 'double area(int)'
    5 | double area(int side) { return side * side; }
      |        ^~~~
main.cpp:4:5: note: old declaration 'int area(int)'

Common mistakes (and the real g++ messages)

Mistake Code What g++ says / what happens Fix
Function defined below main, no prototype withGst(120) in main, definition after error: 'withGst' was not declared in this scope add double withGst(double price); above main
Too few arguments bill(5) for bill(int, double) error: too few arguments to function 'double bill(int, double)' pass both, or give price a default
Using a void result int x = line(); error: void value not ignored as it ought to be call it on its own: line();
Default not at the end bill(double price = 60, int days) error: default argument missing for parameter 2 of 'double bill(double, int)' bill(int days, double price = 60)
Using a local variable outside its function cout << total; in main error: 'total' was not declared in this scope return the value, or store the returned value
Expecting a parameter change to reach the caller addBonus(marks); no error; marks is unchanged marks = addBonus(marks); (or int&, episode 10)
Overloading on return type only int area(int) + double area(int) error: ambiguating new declaration of 'double area(int)' change the parameter list or the name
Ambiguous overloaded call area(4, 2.5) error: call of overloaded 'area(int, double)' is ambiguous area(4.0, 2.5)
Forgetting return in a non-void function double withGst(double p) { p * 1.12; } compiles without -Wall; undefined behaviour: our run crashed with Segmentation fault. With -Wall: warning: no return statement in function returning non-void return p * 1.12;
A function inside main int main() { double withGst(double price) { ... } } error: a function-definition is not allowed here before '{' token define functions outside main

Mini project: Meena's tiffin receipts

line() is void; withGst has a default GST rate of 5%; receipt has a default price of ₹60 and calls another function.

#include <iostream>
#include <string>
using namespace std;
void line() { cout << "-------------------" << endl; }
double withGst(double amount, double rate = 5) {
    return amount + amount * rate / 100;
}
void receipt(string name, int days, double price = 60) {
    cout << name << ": Rs " << withGst(days * price) << endl;
}

int main() {
    line();
    receipt("Ravi", 20);
    receipt("Priya", 22, 75);
    receipt("Arjun", 5);
    line();
    return 0;
}

Output:

-------------------
Ravi: Rs 1260
Priya: Rs 1732.5
Arjun: Rs 315
-------------------
  • Ravi: 20 × 60 = 1200, plus 5% = 1260. Priya: 22 × 75 = 1650, plus 5% = 1732.5. Arjun: 5 × 60 = 300, plus 5% = 315.
  • main now reads like a summary: a line, three receipts, a line. Each rule lives in exactly one place.
  • Try it: add a fourth customer, or call withGst(days * price, 12) to use a 12% rate.

Practice

  1. Write double toFahrenheit(double c) and call it for 0, 37 and 100.
  2. Write void stars(int n) that prints n stars on one line (use a loop from episode 6).
  3. Overload maxOf for two ints and for three ints.
  4. Write bool isEven(int n) and test it on 10 and 7.
Solution

1. Output: 32, 98.6, 212.

#include <iostream>
using namespace std;

double toFahrenheit(double c) {
    return c * 9 / 5 + 32;
}

int main() {
    cout << toFahrenheit(0) << endl;
    cout << toFahrenheit(37) << endl;
    cout << toFahrenheit(100) << endl;
    return 0;
}

2. Output: *** and *****.

#include <iostream>
using namespace std;

void stars(int n) {
    for (int i = 1; i <= n; i++) {
        cout << "*";
    }
    cout << endl;
}

int main() {
    stars(3);
    stars(5);
    return 0;
}

3. The three-int version reuses the two-int version. Output: 9 and 9.

#include <iostream>
using namespace std;

int maxOf(int a, int b) {
    if (a > b) return a;
    return b;
}

int maxOf(int a, int b, int c) {
    return maxOf(maxOf(a, b), c);
}

int main() {
    cout << maxOf(4, 9) << endl;
    cout << maxOf(4, 9, 7) << endl;
    return 0;
}

4. n % 2 == 0 is already a bool, so return it directly. Output: true and false.

#include <iostream>
using namespace std;

bool isEven(int n) {
    return n % 2 == 0;
}

int main() {
    cout << boolalpha;
    cout << isEven(10) << endl;
    cout << isEven(7) << endl;
    return 0;
}

Quick quiz

What does this print?

void addOne(int n) {
    n = n + 1;
}

int main() {
    int x = 5;
    addOne(x);
    cout << x << endl;
}
  • A. 5
  • B. 6
  • C. Compile error
  • D. A garbage value
Answer

A: 5 (verified). x is passed by value: n is a copy of x. Adding 1 to the copy doesn't touch x. With void addOne(int& n) it would print 6.

Interview questions

  • What is a function and why use one? A named, reusable block of code that does one job. It removes duplication (one rule, one place), makes code readable (receipt("Ravi", 20)), and lets you test pieces separately.
  • What is the difference between a parameter and an argument? A parameter is the variable in the function's definition (price); an argument is the value passed in a call (120).
  • What is the difference between a declaration and a definition? A declaration (prototype) states the name, parameter types and return type, ending with ;. A definition also supplies the body. A function may be declared many times but defined once.
  • Why do we need prototypes? The compiler reads top to bottom and must know a function's signature before a call. A prototype allows the definition to come later (or in another file).
  • What is pass by value? The argument's value is copied into the parameter; changes inside the function don't affect the caller's variable. Pass by reference (int&) gives the function the original.
  • What is a local variable? A variable declared inside a function (or block); it exists only there and is destroyed when the function returns.
  • What are default arguments, and what is the rule? Values used when the caller omits an argument. They must be the trailing (rightmost) parameters.
  • What is function overloading? Several functions with the same name but different parameter lists (number or types). The compiler chooses one at compile time from the arguments (overload resolution). It is a form of compile-time polymorphism.
  • Can functions be overloaded on return type alone? No: int f(int) and double f(int) conflict, because a call f(5) can't tell them apart.
  • When is an overloaded call ambiguous? When two or more candidates are equally good matches after conversions, e.g. area(4, 2.5) with area(int, int) and area(double, double).

Glossary

Term Plain meaning Example
Function A named block of code that does one job, reusable by calling its name withGst
Define (definition) Write the function's full code: signature plus body double withGst(double price) { return price * 1.12; }
Call Use a function by its name with round brackets; the caller pauses until it returns withGst(120)
Caller The code that calls a function main calling withGst
Parameter A variable in the function's definition that receives an input price in withGst(double price)
Argument The actual value passed in a call 120 in withGst(120)
Parameter list The parameters inside the round brackets, separated by commas (int days, double price)
Return value The answer a function hands back to its caller 134.4
return Sends a value back and ends the function at once return price * 1.12;
Return type The type of the value a function returns, written before its name double
Body The code between a function's curly braces { return price * 1.12; }
void "Empty": the return type of a function that returns nothing void line()
Declaration / prototype A function's first line ending in ;, announcing it before its definition double withGst(double price);
Signature A function's name plus its parameter types bill(int, double)
Scope The part of the code where a name can be used total is in scope only inside bill
Local variable A variable created inside a function; it disappears when the function returns double total in bill
Pass by value Passing a copy of the argument's value; the original is unchanged addBonus(marks) leaves marks at 78
Reference (&) Another name for an existing variable; a reference parameter works on the original (episode 10) void addBonus(int& marks)
Default argument A value a parameter takes when the caller leaves it out double price = 60
Function overloading Several functions with the same name but different parameter lists area(int), area(int, int)
Overload resolution The compiler choosing which overloaded version a call means, from the arguments area(4.5, 2.5) → area(double, double)
Ambiguous call A call that matches two overloads equally well, so the compiler refuses area(4, 2.5)
Hard-coded / duplicated code The same value or formula written in several places * 1.05 three times
Undefined behaviour Code whose result C++ doesn't define: it may work, print garbage or crash a non-void function without return
boolalpha Makes cout print true/false instead of 1/0 cout << boolalpha << isEven(10);
Compile error A mistake g++ finds before the program runs; no program is produced 'withGst' was not declared in this scope

Summary

  • Copy-pasted rules break when one copy is missed. Write the rule once as a function and call it everywhere.
  • A function = return type, name, (parameters), { body }. return sends the answer back and ends the function.
  • Arguments fill parameters in order; too few gives too few arguments to function.
  • void functions return nothing; using their "result" gives void value not ignored as it ought to be.
  • The compiler reads top to bottom: a function used before it is defined needs a prototype, or you get was not declared in this scope.
  • Pass by value: functions get copies, so they can't change the caller's variables. Return the new value (or use &, episode 10).
  • Local variables live only inside their function.
  • Default arguments fill in missing values, and must come last.
  • Overloading: one name, different parameter lists (number or types); the return type alone is not enough; fix ambiguous calls by making the argument types exact.

Next episode: arrays and strings. What if Meena has 60 customers, or a teacher has marks for 60 students? Sixty separate variables? Next time you'll invent arrays, and work with strings properly.