0% found this document useful (0 votes)
10 views

Chapter 3 - Functions in C++

Uploaded by

basur00basur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Chapter 3 - Functions in C++

Uploaded by

basur00basur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

College of Business, Science &Technology (CBST), Mymensingh

Department of Computer Science and Engineering

Object Oriented Programming (OOP)

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";}
};

Q.2. Rules of Function Overloading in C++.

Different parameters or three different conditions :

1. These functions have different parameter type.


sum(int a, int b)
sum(double a, double b)

2. These functions have a different number of parameters.


sum(int a, int b)
sum(int a, int b, int c)

3. These functions have a different sequence of parameters.


sum(int a, double b)
sum(double a, int b)

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.

Function Overloading Function Overriding

Function Overriding is the redefinition of base


Function Overloading provides multiple definitions
class function in its derived class with same
of the function by changing signature.
signature.

An example of compile time polymorphism. An example of run time polymorphism.

Function signatures should be different. Function signatures should be the same.

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.

In function overriding, we need an inheritance


In function overloading, we don’t need inheritance.
concept.

Q.3 When function overloading needed. Explain with example.


Function overloading is needed when we want to perform similar operations on different types or
numbers of parameters, providing a more intuitive and flexible interface for users of the functions. It
allows a function to handle various data types and parameter lists without the need to create multiple
function names.

When to Use Function Overloading:

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;

void add(int a, int b)


{
cout << "sum = " << (a + b);
}

void add(double a, double b)


{
cout << endl << "sum = " << (a + b);
}

int main( )
{
add(10, 2);
add(5.3, 6.2);

return 0;
}

Output:
sum = 12
sum = 11.5

Q.4 What is inline function?

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.

Syntax for an inline function:

inline return_type function_name(parameters)


{
// 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.

Inline function is the optimization technique used by the compilers .

Advantages :-

1) It does not require function calling overhead .

2) It also save overhead of variables push on the stack , while function calling .

3) It also save overhead of return call from a function .

4) It increases locality of reference by utilizing instruction cache .

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 .

Q.6 Situation where inline function doesn't work.

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:

1. If a function contains a loop. (for, while and do-while)


2. If a function contains static variables.
3. If a function is recursive.
4. If a function return type is other than void, and the return statement doesn’t exist in a function body.
5. If a function contains a switch or goto statement.
Q. What is macro?
Macro is also called preprocessors directive. The macros are defined by the #define keyword. Before the
program compilation, the preprocessor examines the program whenever the preprocessor detects the
macros then preprocessor replaces the macro by the macro definition.

Syntax of Macro:

#define MACRO_NAME Macro_definition

Q.7 How does inline function differ from preprocessor 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.

S.NO Inline Macro


Whereas the macros are defined by the #define
1. An inline function is defined by he inline keyword.
keyword
Through inline function, the class’s data members Whereas macro can’t access the class’s data
2.
can be accessed. members.
In the case of inline function, the program can be Whereas in the case of macros, the program can’t
3.
easily debugged. be easily debugged.
Whereas in the case of macro, the arguments are
In the case of inline, the arguments are evaluated
4. evaluated every time whenever macro is used in the
only once.
program.
In C++, inline may be defined either inside the Whereas the macro is all the time defined at the
5.
class or outside the class. beginning of the program.
In C++, inside the class, the short length functions
6. While the macro is specifically defined.
are automatically made the inline functions.
7. Inline is not as widely used as macros. While the macro is widely used.
While the macro is very much used in competitive
8. Inline is not used in competitive programming.
programming.
Inline function is terminated by the curly brace at While the macro is not terminated by any symbol,
9.
the end. it is terminated by a new line.

Q.8 What is volatile function?


Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile
object.
A member function invoked by a volatile object. A volatile object’s value can be changes by external
parameters which are not under the control of the program.
Q.9 Normal function.

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.

Syntax of the Normal Function:

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.

Q.11. Advantages of function prototyping in C++.

Here’s a simple, pointwise explanation of the advantages of function prototyping in C++:

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.

Q.12 What do you mean by default argument? With example.

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;
}

Q.13 Describe about ambiguity in case of default argument with example.

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.

void print(int a, int b = 5, int c = 10);


print(3); // Is 3 assigned to 'a', 'b', or 'c'?

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);
};

MyClass obj(5); // Is '5' assigned to 'a' or 'b'?

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);
}

Q.15 When will you make a function inline ? Why?

Inline functions in are used to reduce the overhead of function calls by embedding the function's code
directly at each call site.

When to make function inline-

1. Function is small and frequently called: Inline functions are ideal for simple, short functions like
getters, setters, or basic arithmetic operations.

2. Function is in performance-critical code: Inlining can be beneficial in loops or sections where


function call overhead impacts performance.

Why Make a Function Inline-

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”.

Parameter Call By Value Call By Reference


Naming The function is invoked by passing the The function is invoked by passing the
Convention parameter’s value in Call by Value, which is parameter’s reference (i.e., the location of
why it has this name. variables) in Call by Reference, which is why it
has this name.
Impact of any changes made to the function’s argument changes to the function’s argument are
Changes do not affect the passed parameter as the value reflected in the passed parameter as both refer
of the parameter is copied. to the same location.
Type of Passing Call by Value passes a copy of the variable . Call by Reference passes the variable itself .
Memory the actual arguments and passed parameters of the actual arguments and passed parameters of
Location a function refer to different memory locations. a function refer to the same memory location.
Value In Call by Value, the original value is not In Call by Reference, the original value is
Modification modified. modified.
Method of In Call by Value, the values of the variables are In Call by Reference, the address of the
Passing passed using a simple technique. variables is stored using pointer variables.

Q.17 When do we need to use default argument in a function?

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.

Avoiding Function Overloading: In some languages, function overloading is common. default


arguments can simplify this by using one function with optional parameters instead of multiple
overloaded functions.

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.

You might also like