C++ Functions
What Is a Function in C++?
A function in C++ is a block of organized code that performs a specific task. Instead of writing the same logic multiple times, you can define a function once and use it wherever you need that behavior.
Functions are powerful because they break large programs into smaller, manageable parts. Each function focuses on one job — whether that's displaying text, doing math, or checking a condition.
Why Use Functions?
- Avoids Repetition: Instead of copying code again and again, reuse a function to save effort.
- Keeps Code Clean: Organizes logic into separate units, making programs easier to read and understand.
- Simplifies Debugging: If something goes wrong, you only have to check the function instead of the whole program.
- Promotes Reuse: A well-written function can be used in multiple places or even other projects.
Basic Function Structure
Here’s a unique breakdown of how a typical C++ function looks
returnType functionName(parameters) {
// Instructions go here
} - returnType: Type of value the function sends back (e.g., int, void, float).
- functionName: Unique label for the function.
- parameters: Optional inputs the function needs to work with.
Function with a Return Value Example
#include <iostream>
int square(int number) {
return number * number;
}
int main() {
int result = square(5);
std::cout << "Square is: " << result << "\n";
return 0;
} Explantion
- int square(int number) defines a function that takes one input and gives back a number.
- The calculation number * number happens inside.
- The return sends the result back to where the function was called.
- In main(), the function is used to find the square of 5 and print it.
C++ Function Parameters
In C++, parameters (or arguments) are the values you pass to a function. These values let a function work with different data each time it runs. Parameters allow your code to be flexible and customizable.
Types of Function Parameters
| Parameter Type | Distinct Description |
|---|---|
| Formal Parameters | Names listed in the function’s definition that act as placeholders for input values. |
| Actual Parameters | The real data or variables sent when you call the function. |
| Default Arguments | Parameters that take a set value if no input is provided during the function call. |
| Constant Parameters | Inputs marked const to stop them from being changed inside the function. |
| Call by Value | A copy of the data is passed; changes inside the function don’t affect the original. |
| Call by Reference | The actual memory address is shared; changes in the function also affect the original variable. |
Examples of Each Parameter Type
1. Default Argument Example
#include <iostream>
void greet(std::string name = "Guest") {
std::cout << "Hello, " << name << "!\n";
}
int main() {
greet(); // Uses default
greet("Ayaan"); // Uses provided value
return 0;
} 2. Constant Parameter Example
void displayMessage(const std::string message) {
std::cout << "Note: " << message << "\n";
} 3. Call by Value Example
void update(int num) {
num = num + 10;
}
int main() {
int x = 5;
update(x);
std::cout << x; // Still prints 5
} 4. Call by Reference Example
void modify(int &ref) {
ref += 5;
}
int main() {
int value = 3;
modify(value);
std::cout << value; // Now prints 8
} Types of Functions in C++
| Type | Unique Explanation |
|---|---|
| Library Function | Comes with standard headers and solves common tasks (e.g., pow(), sqrt()). |
| Custom Function | Made by the programmer to fit a specific purpose. |
| Void Function | Performs a job but doesn’t deliver back a value. |
| Result-Returning Function | Outputs a value to the caller once its task completes. |
| Inline Function | Small function where the compiler places code directly at the call spot for speed. |
| Recursive Function | A function that runs itself again with a new input. |
Function Overriding
Function overriding happens in inheritance, where a derived (child) class rewrites a method already declared in the base (parent) class. The overridden version replaces the parent’s behavior, allowing the child to act differently.
- It's a way to customize or extend behavior for a subclass without changing the base logic.
Function Overriding Example
#include <iostream>
class Animal {
public:
void sound() {
std::cout << "Animal makes noise\n";
}
};
class Dog : public Animal {
public:
void sound() {
std::cout << "Dog barks\n";
}
};
int main() {
Dog d;
d.sound(); // Runs overridden method
return 0;
} Notes on Overriding
- Same function name and parameters are required.
- Redefines the original action from the parent.
- Overriding gives more specific behavior in derived classes.
Summary
Functions make your code organized, reusable, and smart. By using different types of parameters, you control how data flows in and out. With default values, constant restrictions, and reference handling, you write functions that adapt to different tasks. And with overriding, you give child classes the power to adjust inherited behavior — all while keeping your code neat and meaningful.
Prefer Learning by Watching?
Watch these YouTube tutorials to understand C++ Tutorial visually:
What You'll Learn:
- 📌 C++ Functions Tutorial For Beginners | Functions In C++ | C++ Programming Tutorial | Simplilearn
- 📌 Learn C++ With Me #20 - Functions