Chapter 3 - Functions in C++
Chapter 3 - Functions in C++
Chapter - F u n c t i o n s i n C + +
Prepared by Md.
Masum Billah
Lecturer, Dept. of CSE, CBST
Mobile: 01793200796
Functions in C++
Q.1 What do you mean by function overloading and function overriding.
Function overloading allows the creation of multiple functions with the same name but different
parameter lists within the same scope. These functions are differentiated based on the number or type of
their parameters. It enables a more intuitive and flexible way of defining functions that perform similar
tasks but with different inputs.
Example-
void area (int a);
void area(int a, int b);
Function overriding allows a subclass to provide a specific implementation of a method that is already
defined in its superclass. This is used to change or extend the behavior of the inherited method.
Class a
{
public:
virtual void display(){ cout << "hello"; }
};
Class b:public a
{
public:
void display(){ cout << "bye";}
};
The above three cases are valid cases of overloading. We can have any number of functions, but
remember that the parameter list must be different. For example:
Q.2 Difference between Function Overloading vs Function Overriding.
Overloaded functions are in same scope. Overridden functions are in different scopes.
Overloading is used when the same function has to Overriding is needed when derived class
behave differently depending upon parameters function has to do some different job than the
passed to them. base class function.
A function has the ability to load multiple times. A function can be overridden only a single time.
1. Same Operation on Different Data Types: When the same logical operation needs to be performed
on different data types.
2. Variety of Input Parameters: When a function needs to handle different numbers of input
parameters.
3. Code Readability and Maintainability: When overloading improves the readability and
maintainability of the code by grouping similar functionalities under a single function name.
Example-
#include <iostream>
using namespace std;
int main( )
{
add(10, 2);
add(5.3, 6.2);
return 0;
}
Output:
sum = 12
sum = 11.5
An inline function is a function that is expanded in line when it is invoked. When the compiler compiles
the program, the function call is replaced with the actual code of the function. This can potentially
increase the efficiency of the program by eliminating the overhead associated with function calls, such
as stack manipulation and jumping to the function code.
Inline functions are a useful tool for optimizing performance by reducing function call overhead. They
are best used for small, frequently called functions and should be used carefully to avoid code bloat.
Q.5 What are the Advantages and Disadvantages of inline function.
Advantages :-
2) It also save overhead of variables push on the stack , while function calling .
5) After in-lining compiler can also apply intra procedural optmization if specified . This is the most
important one , in this way compiler can now focus on dead code elimination , can give more stress on
branch prediction , induction variable elimination etc .
Disadvantages :-
1) May increase function size so that it may not fit on the cache , causing lots of chance miss .
2) After in-lining function if variables number which are going to use register increases than they may
create overhead on register variable resource utilization .
3) It may cause compilation overhead as if some body changes code inside inline function than all
calling location will also be compiled .
4) If used in header file , it will make header file size large and may also make it unreadable .
5) If somebody used too many inline function resultant in a larger code size than it may cause thrashing
in memory. More and more number of page fault bringing down program performance.
6) Its not useful for embedded system where large binary size is not preferred at all due to memory size
constraints .
The inline keyword only sends a request, not a command, to the compiler. The compiler may ignore this
request if the function definition is too large or too complicated and compile the function as a normal
function.
Some of the situation where inline expansion may not work are:
Syntax of Macro:
The main difference between inline and macro functions is that inline functions are parsed by the
compiler, whereas macros in a program are expanded by the preprocessor. The keyword "inline" is used
to define an inline function, whereas "#define" is used to define a macro.
Regular or normal functions are the most common functions in C++. They are defined outside of any
class and have a separate block of code called when the function is invoked. When the normal function
is called, the compiler creates a new stack frame for the functions to track the function calls. This
function has a return type.
return_type function_name(parameters) {
// Function code
return result;
}
It will return some value after doing computation. It takes some values whenever it is called. Those
values are generally called arguments. The function will work on those arguments and return the output.
There will be no return type for some normal functions, which means those have a void return type.
1. Type Checking: Ensures the arguments passed to a function are of the correct type, preventing errors.
2. Call Before Definition: Allows you to use a function before its actual implementation in the code.
3. Code Readability: Gives a clear summary of the function's details (name, return type, parameters)
without needing to see the full code.
4. Supports Large Programs: Helps manage large projects by allowing functions to be declared in
header files and used across multiple source files.
5. Prevents Implicit Declarations: Avoids confusion caused by default return types (like `int`) when a
function is called before it's defined.
6. Function Overloading: Enables using the same function name with different parameters, helping
create cleaner, more flexible code.
A default argument is a value in the function declaration automatically assigned by the compiler if the
calling function does not pass any value to that argument. In case any value is passed, the default value
is overridden.
Example:
#include <iostream>
using namespace std;
int sum(int x, int y, int z = 0, int w = 0) //assigning default values to z, w as 0
{
return (x + y + z + w);
}
int main()
{
// Statement 1
cout << sum(10, 15) << endl;
// Statement 2
cout << sum(10, 15, 25) << endl;
// Statement 3
cout << sum(10, 15, 25, 30) << endl;
return 0;
}
Default arguments are specified in function declarations to allow calling functions without providing
values for certain parameters. default arguments in C++ can lead to ambiguity and unexpected behavior
if not used carefully.
1. Order of Default Arguments: Default arguments are assigned from right to left. If we have multiple
parameters with default values, omitting arguments can cause ambiguity.
Solution: Ensure that functions with default arguments have a clear and unambiguous order, or
consider overloading to provide different sets of default arguments.
3. Constructor Overloading: Constructors with default arguments can lead to ambiguity, especially
when they overload other constructors.
class MyClass {
public:
MyClass(int a, int b = 0);
};
Solution: Minimize constructor overloading with default arguments to prevent confusion. Provide clear
and unambiguous constructors.
Q.14 Write a program in C++ that finds the area of different shape using function overloading.
#include<iostream>
using namespace std;
int area(int s)
{
return(s*s);
}
int area(int l,int b)
{
return(l*b);
}
float area(float r)
{
return(3.14*r*r);
}
float area(float bs,float ht)
{
return((bs*ht)/2);
}
int main()
{
int s,l,b;
float r,bs,ht;
cout<<"Enter side of a square:";
cin>>s;
cout<<"Enter length and breadth of rectangle:";
cin>>l>>b;
cout<<"Enter radius of circle:";
cin>>r;
cout<<"Enter base and height of triangle:";
cin>>bs>>ht;
cout<<"Area of square is"<<area(s);
cout<<"\nArea of rectangle is "<<area(l,b);
cout<<"\nArea of circle is "<<area(r);
cout<<"\nArea of triangle is "<<area(bs,ht);
}
Inline functions in are used to reduce the overhead of function calls by embedding the function's code
directly at each call site.
1. Function is small and frequently called: Inline functions are ideal for simple, short functions like
getters, setters, or basic arithmetic operations.
1. Reduce Function Call Overhead: Inlining eliminates the overhead associated with function calls.
This can be particularly beneficial in performance-critical code where function calls are frequent.
2. Enhance Performance: By integrating the function's code directly into the caller, the compiler can
apply additional optimizations, such as loop unrolling and constant folding, leading to more efficient
execution.
Q.16 Write down the difference between “call by value” and “call by reference”.
Optional Parameters: If a parameter is not always needed and a sensible default value exists, default
arguments allow the caller to skip specifying that parameter.
Providing Common Defaults: When there's a common value most function calls would use, providing
it as a default avoids repetition and reduces the potential for mistakes.
Backward Compatibility: If you're updating a function by adding new parameters, using default
arguments ensures that existing code using the function still works without modification.
Reducing Complexity in Callers: When a function has many parameters but most of them have default
values, it reduces the cognitive load on the caller, who only needs to provide essential inputs.