0% found this document useful (0 votes)
19 views53 pages

C++ Function Prototypes Explained

The document discusses the concept of functions in C++, focusing on function prototypes, definitions, return types, and inline functions. It explains the syntax and purpose of function prototypes, the different types of return values, and the advantages and disadvantages of inline functions. Additionally, it covers default arguments, constant arguments, and function overloading, emphasizing their importance in C++ programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views53 pages

C++ Function Prototypes Explained

The document discusses the concept of functions in C++, focusing on function prototypes, definitions, return types, and inline functions. It explains the syntax and purpose of function prototypes, the different types of return values, and the advantages and disadvantages of inline functions. Additionally, it covers default arguments, constant arguments, and function overloading, emphasizing their importance in C++ programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

2-Functions in C++ - 2030107301

Unit 2 1

Functions in C++ and Working with Objects


Function prototypes are a crucial concept in the C++ programming. They play a fundamental
role in ensuring that the compiler understands how to interpret and use functions within your
code.

A function prototype serves as a declaration that outlines the function's signature, enabling the
compiler to perform necessary checks and optimizations during the compilation process.

What Is A Function Prototype In C++?

A function prototype is a declaration of a function's signature before the


actual function definition.

It provides essential information about the function, such as its name, return type, and the types
of parameters it accepts.

The primary purpose of a function prototype is to inform the compiler about the existence and
details of a function so that it can properly validate and integrate the function call statements in
your code.

Syntax of Function Prototype In C++:

returnType functionName(parameterType1 parameterName1, parameterType2


parameterName2, ...);

 return_type: This specifies the data type of the value that the function will return when it
is executed. It indicates the type of the result produced by the function. Examples of
returnType include int, void, double, char, and user-defined types.
2-Functions in C++ - 2030107301

 function_name: This is the name of the function. It is used for identifying and calling 2
functions in the code. Function names must follow the rules of C++ naming conventions,
such as not containing spaces and starting with a letter or an underscore.

 parameter_type1, parameter_type2, ...: These are the data types of the function's
parameters. Parameters are input values that the function expects to receive when it is
called. Functions can have zero or more parameters. The parameters are given in a
comma-separated list and consist of a data type followed by a parameter name.

 parameterName1, parameterName2, ...: These are the names assigned to the


parameters. Parameter names are used within the function to refer to the values passed
as arguments. They serve as placeholders for the actual data that will be provided when
the function is called.

Type Of Return Values For Function Prototypes In C++

In C++, functions can have various return types, which determine the type of value the function
returns when it is executed. The choice of return type depends on the function's purpose and
what kind of data it needs to provide.

1. Void Return Type:

A function with a return type void does not return any value. It is often used for functions that
perform actions without producing a result.

Syntax:

void functionName(parameters);

Example:

void greetUser(const std::string& name) {


std::cout << "Hello, " << name << "!" << std::endl;
}
2-Functions in C++ - 2030107301

int main() { 3
greetUser("Alice");
return 0;
}

2. Integral Return Types (e.g., int, char, bool, long, etc.):

These return types are used when the function needs to return an integer-based result, such as
numbers or character codes.

Syntax:

returnType functionName(parameters);

Example:
int add(int a, int b)

{
return a + b;

}
int main() {
int result = add(5, 3);
std::cout << "The sum is: " << result << std::endl;
return 0;
}

3. Floating-Point Return Types (e.g., float, double):

These return types are used when the function needs to return decimal or floating-point values.

Syntax:

returnType functionName(parameters);
2-Functions in C++ - 2030107301

Example: 4

double divide(double x, double y) {


if (y != 0.0) {
return x / y;
}

else {
std::cerr << "Error: Division by zero." << std::endl;
return 0.0;}
}
int main() {
double result = divide(10.0, 2.0);
std::cout << "Result of division: " << result << std::endl;
return 0;
}

4. Pointer Return Types:

Functions can return pointers to various types, including user-defined types. This is useful when
you want to return references to dynamically allocated memory or objects.

Syntax:

returnType* functionName(parameters);

Example:

// C++ program to return a pointer from a function

#include <iostream>

using namespace std;

// declaring the function with dynamic memory

int* createArray(int size)

int* arr = new int[size];

for (int i = 0; i < size; i++) {

arr[i] = i;

}
2-Functions in C++ - 2030107301

// Return the pointer to the array 5

return arr;

int main()

// Function call

int* myArray = createArray(5);

// Use the array

cout << "Array elements: ";

for (int i = 0; i < 5; i++) {

cout << myArray[i] << " ";

cout << endl;

// Properly deallocate memory

delete[] myArray;

return 0;

Output

Array elements: 0 1 2 3 4

5. Reference Return Types:

Functions can return references to objects. This is often used when you want to return by
reference to an existing object or to enable an assignment statement to the result.

Syntax:

returnType& functionName(parameters);

Example:
2-Functions in C++ - 2030107301

int& getMax(int& a, int& b) { 6


return (a > b) ? a : b;
}
int main() {
int x = 10;
int y = 5;
int& maxRef = getMax(x, y);
maxRef = 100; // Changes the value of x
std::cout << "x: " << x << std::endl;
std::cout << "y: " << y << std::endl;
return 0;
}

Function Definition & Function Prototype In C++

Function Definition In C++

A function definition in C++ is the actual implementation of a function's behavior. It includes the
code that gets executed when the function is called. A function definition typically consists of-

 Return Type: The data type of the value that the function will return (if any). If a function
doesn't return a value, its return type is specified as void.

 Function Name: The unique identifier for the function by which it can be called in the
program.

 Parameter List: The list of input parameters (that allow you to pass values) that the
function accepts. These parameters are enclosed in parentheses and separated by
commas.
2-Functions in C++ - 2030107301

 Function Body: The actual set of statements enclosed within curly braces {} that define 7
what the function does when it is called.

Examples Of Function Prototype In C++

#include <iostream>

// Function prototype (declaration)


int add(int a, int b);

int main() {
int num1 = 5;
int num2 = 3;

// Calling the add function


int sum = add(num1, num2);

std::cout << "The sum of " << num1 << " and " << num2 << " is: " << sum << std::endl;

return 0;
}

// Function definition
int add(int a, int b) {
return a + b;
}

Output:

The sum of 5 and 3 is: 8


2-Functions in C++ - 2030107301

Explanation: 8

In this example:

1. We start by including the <iostream> header for input and output operations.

2. Next, we declare the function prototype for the add function with the signature int add(int
a, int b).

3. This informs the compiler that there will be a function called add that takes two int
parameters and returns an int. This allows us to call the add function within the main
function even though the add function's definition appears later in the code.

4. Inside the main function, we have two integer variables num1 and num2. We call the add
function with these variables as arguments and store the result in the sum variable.

5. Finally, we define the add function, which simply adds the two input integers and returns
the result.

Feature Function Prototype Function Definition

Informs the compiler about the function's


Provides the actual implementation
Purpose signature before its actual
of the function's behavior.
implementation.

return_type
Syntax return_type function_name(parameters); function_name(parameters) { /*
Function body */ }

Typically placed at the beginning of a


Placed in the same file as the
C++ file, often in header files (.h) or
Placement function prototype or in a separate
directly in source files (.cpp) before using
file.
the function.

Specifies the data type of the value


Return It must match the data type specified
returned by the function (e.g., int, void,
Type in the entire function prototype.
etc.).
2-Functions in C++ - 2030107301

Feature Function Prototype Function Definition 9

Function It must match the name specified in


The unique identifier for the function.
Name the prototype.

Parameter Lists the input parameters the function Must match the parameters specified
List accepts, including their data types. in the prototype, including data types.

Contains the actual set of statements


Function It is not included, i.e., only the function
that define what the function does
Body signature is provided.
when called.

Allows you to call the function before its Provides the actual implementation
Usage definition, enabling modularity and of the function, and it must follow the
separate compilation. prototype's signature exactly.

Inline Functions in C++


An inline function is a function that is expanded in line when it is called. When the inline
function is called whole code of the inline function gets inserted or substituted at the point of the
inline function call.

This substitution is performed by the C++ compiler at compile time. An inline function may
increase efficiency if it is small.

Syntax:

inline return-type function-name(parameters)


{
// function code
}
2-Functions in C++ - 2030107301

10

Remember, inlining is only a request to the compiler, not a command. The compiler can ignore
the request for inlining.

The compiler may not perform inlining in such circumstances as:

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.

Why Inline Functions are Used?

When the program executes the function call instruction the CPU stores the memory address of
the instruction following the function call, copies the arguments of the function on the stack, and
finally transfers control to the specified function.

The CPU then executes the function code, stores the function return value in a predefined
memory location/register, and returns control to the calling function. This can become overhead
if the execution time of the function is less than the switching time from the caller function to
called function (callee).
2-Functions in C++ - 2030107301

For functions that are large and/or perform complex tasks, the overhead of the function call is 11
usually insignificant compared to the amount of time the function takes to run.

However, for small, commonly-used functions, the time needed to make the function call is often
a lot more than the time needed to actually execute the function’s code.

This overhead occurs for small functions because the execution time of a small function is less
than the switching time.

Inline functions Advantages:

1. Function call overhead doesn’t occur.

2. It also saves the overhead of push/pop variables on the stack when a function is called.

3. It also saves the overhead of a return call from a function.

4. When you inline a function, you may enable the compiler to perform context-specific
optimization on the body of the function. Such optimizations are not possible for normal
function calls. Other optimizations can be obtained by considering the flows of the calling
context and the called context.

5. An inline function may be useful (if it is small) for embedded systems because inline can
yield less code than the function called preamble and return.

Inline function Disadvantages:

1. If after function inlining variable numbers increase drastically then it would surely cause
overhead on register utilization.

2. If you use too many inline functions then the size of the binary executable file will be
large, because of the duplication of the same code.

3. Too much inlining can also reduce your instruction cache hit rate, thus reducing the
speed of instruction fetch from that of cache memory to that of primary memory.

4. The inline function may increase compile time overhead if someone changes the code
inside the inline function then all the calling location has to be recompiled because the
compiler would be required to replace all the code once again to reflect the changes,
otherwise it will continue with old functionality.

5. Inline functions may not be useful for many embedded systems. Because in embedded
systems code size is more important than speed.

6. Inline functions might cause thrashing because inlining might increase the size of the
binary executable file. Thrashing in memory causes the performance of the computer to
degrade. The following program demonstrates the use of the inline function.
2-Functions in C++ - 2030107301

DEFAULT ARGUMENT 12

A default argument provides a default value for a function parameter. If a caller does not
provide a value for that parameter, the default value is used.

Usage: To allow the function to be called with fewer arguments than defined, providing default
values for some parameters.
Syntax: You define default values in the function prototype or definition.

Example of Default Argument

Key Points:

1. Optional parameters: With default arguments, a function can be called with fewer
arguments. The missing arguments are filled with the default values.
2. Default arguments must be provided from right to left.
3. For example, if the function has multiple parameters, the default value can only be omitted

For the rightmost arguments.


2-Functions in C++ - 2030107301

13

We can understand the working of default arguments from the image above:
1. When temp() is called, both the default parameters are used by the function.
2. When temp(6) is called, the first argument becomes 6 while the default value is used for the
second parameter.
3. When temp(6, -2.3) is called, both the default parameters are overridden, resulting in i = 6
and f = -2.3.
4. When temp(3.4) is passed, the function behaves in an undesired way because the second
argument cannot be passed without passing the first argument.

Therefore, 3.4 is passed as the first argument. Since the first argument has been defined as
int, the value that is actually passed is 3.

CONSTANT ARGUMENT
A constant argument(or const parameter) is a function parameter that is declared as constant.
This means the parameter cannot be modified inside the function. It ensures that the function
does not accidentally modify the argument passed to it.

Usage: To prevent the modification of an argument inside the function, which is especially
useful when passing large objects by reference to avoid accidental changes?
Syntax: You use the `const` keyword before the parameter in the function declaration.
2-Functions in C++ - 2030107301

14

Example of Constant Argument:

Key Points:
Prevents modification: The `const` keyword ensures that the function does not change the
value of the parameter.

Useful for large objects: When passing objects by reference or pointer, marking them as
`const` ensures they won’t be altered inside the function.
2-Functions in C++ - 2030107301

15

FUNCTION OVERLOADING

Function overloading in C++ is a feature that allows the creation of multiple functions with the
same name but with different parameters (either in number, type, or both).
The compiler differentiates between these overloaded functions based on the number or types
of arguments passed to them.

Key Points:
1. Same Function Name: All overloaded functions have the same name.
2. Different Parameter Lists: Overloading is achieved by changing the number or type of
parameters in the function signature.
3. Return Type: The return type of the overloaded functions can be different, but it does not
play a role in differentiating the functions. Function overloading depends only on the
parameters.

Advantages of Function Overloading:

1. Code Readability: Allows using the same function name for different tasks, improving code
readability.
2. Maintainability: Reduces the need for creating different function names for similar
operations.
3. Flexibility: Makes it easier to work with functions that perform similar tasks with different
types or numbers of inputs.

Explantions:

1. add(int a, int b): This function adds two integers.


2. add(float a, float b): This function adds two floating-point numbers.
3.add(int a, int b, int c): This function adds three integers.

The C++ compiler selects the appropriate function based on the arguments passed. For
example:
If you pass two integers (add(10, 20)), the first version is called.
If you pass two floats (add(5.5f, 6.5f)), the second version is called.
If you pass three integers (add(1, 2, 3)), the third version is called.
2-Functions in C++ - 2030107301

16

Rules for Function Overloading:


• Different Number of Parameters: Functions can have different numbers of parameters.
• Different Types of Parameters: Functions can have the same number of parameters, but
with different data types.
• Different Order of Parameters: Functions can have parameters of the same types, but in
different orders
2-Functions in C++ - 2030107301

17

What is a Class in C++?


A class is a user-defined data type, which holds its own data members and member functions,
which can be accessed and used by creating an instance of that class. A C++ class is like a
blueprint for an object.

For Example: Consider the Class of Cars. There may be many cars with different names and
brands but all of them will share some common properties like all of them will have 4 wheels,
Speed Limit, Mileage range, etc. So here, the Car is the class, and wheels, speed limits, and
mileage are their properties.
2-Functions in C++ - 2030107301

18
A Class is a user-defined data type that has data members and member functions.

Data members are the data variables and member functions are the functions used to
manipulate these variables together, these data members and member functions define the
properties and behavior of the objects in a Class.

In the above example of class Car, the data member will be speed limit, mileage, etc, and
member functions can be applying brakes, increasing speed, etc.

But we cannot use the class as it is. We first have to create an object of the class to use its
features. An Object is an instance of a Class.

Note: When a class is defined, no memory is allocated but when it is instantiated (i.e. an
object is created) memory is allocated.

Defining Class in C++

A class is defined in C++ using the keyword class followed by the name of the class. The
following is the syntax:

class ClassName {

access_specifier:

// Body of the class

};

Here, the access specifier defines the level of access to the class’s data members.

Example

class ThisClass {

public:
2-Functions in C++ - 2030107301

int var; // data member 19

void print() { // member method

cout << "Hello";

};

What is an Object in C++?


When a class is defined, only the specification for the object is defined; no memory or storage is
allocated. To use the data and access functions defined in the class, you need to create objects.

When a class is defined, only the specification for the object is defined; no memory or storage is
allocated. To use the data and access functions defined in the class, you need to create objects.

Syntax to Create an Object

We can create an object of the given class in the same way we declare the variables of any
other inbuilt data type.

ClassName ObjectName;

Example

MyClass obj;

In the above statement, the object of MyClass with name obj is created.

Accessing Data Members and Member Functions

The data members and member functions of the class can be accessed using the dot(‘.’)
operator with the object. For example, if the name of the object is obj and you want to access
the member function with the name printName() then you will have to write:

obj.printName()

// Define a class named 'Person'

#include<iostream>

Using namespace std;

class Person {
2-Functions in C++ - 2030107301

public: 20

// Data members

string name;

int age;

// Member function to introduce the person

void introduce()

cout << "Hi, my name is " << name << " and I am "

<< age << " years old." << endl;

};

int main()

// Create an object of the Person class

Person person1;

// accessing data members

person1.name = "Alice";

person1.age = 30;

// Call the introduce member method

person1.introduce();

return 0;

Output

Hi, my name is Alice and I am 30 years old.


2-Functions in C++ - 2030107301

Access Modifiers(Specifiers) 21

In C++ classes, we can control the access to the members of the class using Access Specifiers.
Also known as access modifier, they are the keywords that are specified in the class and all the
members of the class under that access specifier will have particular access level.

In C++, there are 3 access specifiers that are as follows:

Public: Members declared as public can be accessed from outside the class.

Private: Members declared as private can only be accessed within the class itself.

Protected: Members declared as protected can be accessed within the class and by derived
classes.

If we do not specify the access specifier, the private specifier is applied to every member by
default.

// C++ program to demonstrate accessing of data members

#include <iostream>

using namespace std;

class Person {

private:

string Personname;

// Access specifier

public:

// Member Functions()

void setName(string name)

Personname = name;

void printname()

cout << "Personname is:" << Personname;


2-Functions in C++ - 2030107301

} 22

};

int main()

// Declare an object of class Persons

Persons obj1;

// accessing data member

// cannot do it like: obj1.Personname = "Abhi";

obj1.setName("Abhi");

// accessing member function

obj1.printname();

return 0;

Personname is:Abhi

Member Function in C++ Classes


There are 2 ways to define a member function:

 Inside class definition

 Outside class definition

Till now, we have defined the member function inside the class, but we can also define the
member function outside the class. To define a member function outside the class definition,

 We have to first declare the function prototype in the class definition.

 Then we have to use the scope resolution:: operator along with the class name and
function name.

Example

// C++ program to demonstrate member function

// definition outside class


2-Functions in C++ - 2030107301

#include <iostream> 23

using namespace std;

class Person {

public:

string Personname;

int id;

// printname is not defined inside class definition

void printname();

// printid is defined inside class definition

void printid() { cout << "Person id is: " << id; }

};

// Definition of printname using scope resolution operator

// ::

void Person::printname()

cout << "Person name is: " << Personname;

int main()

Person obj1;

obj1. Personname = "xyz";

obj1.id = 15;
2-Functions in C++ - 2030107301

24
// call printname()

obj1.printname();

cout << endl;

// call printid()

obj1.printid();

return 0;

Output:

Person name is: is: xyz

Person id is: 15

Memory Allocation of Objects and Data Members


2-Functions in C++ - 2030107301

25
Array in class
An array within a class in C++ is a situation where an array is declared as a data member of a
class.

This allows each object of the class to store multiple elements of a particular data type within
the class.

It’s useful when you want to represent a collection of values associated with each object (like a
student's marks, a list of prices, etc.).

Example: Array within a Class

#include <iostream>

using namespace std;

class Student {

private:

string name;

int marks[5]; // Array within the class to store marks of 5 subjects

public:

// Function to set student details and marks

void setDetails(string n, int m[]) {

name = n;

for (int i = 0; i < 5; i++) {

marks[i] = m[i]; // Storing marks in the array

// Function to display student details and marks

void displayDetails() {

cout << "Name: " << name << endl;


2-Functions in C++ - 2030107301

cout << "Marks: "; 26

for (int i = 0; i < 5; i++) {

cout << marks[i] << " "; // Displaying marks from the array

cout << endl;

};

int main() {

Student student1;

// Marks for the student

int marks[5] = {85, 90, 78, 88, 76};

// Set the details of the student

student1.setDetails("John", marks);

// Display the details of the student

student1.displayDetails();

return 0;

Explanation:

1. Array within the Class:

In the `Student` class, the `marks[5]` array is declared as a private data member. This allows

each student object to store 5 marks.

The array size is fixed at 5, so each student will have 5 marks associated with them.

2. setDetails() Function:

This public member function takes a name and an array of marks as parameters and assigns

them to the corresponding data members of the class.


2-Functions in C++ - 2030107301

27
3. displayDetails() Function:

- This function displays the student's name and their marks by accessing the array elements.

4. Main Function:

An array of marks is created in the `main()` function and passed to the `setDetails()` function

to set the marks for the student object `student1`.

The details are then displayed using the displayDetails() function.

Output:

Name: John

Marks: 85 90 78 88 76

Advantages of Using Arrays within a Class:

1. Allows handling multiple values for each object.


2. Useful for scenarios where an entity needs to store multiple related values (e.g., student
marks, employee salaries, etc.).
3. Organizes data neatly within objects, encapsulating the array inside the class.

an **array of objects** refers to a collection of multiple objects of the same class stored in
contiguous memory locations, similar to an array of fundamental data types. Each element of
the array represents an individual object of the class. This is useful when you want to manage
multiple objects together, such as managing records of students, employees, etc.

### Syntax:

```cpp

class ClassName {

// Class members

};
2-Functions in C++ - 2030107301

// Declaring an array of objects 28

ClassName objArray[size];

```

### Example: Array of Objects in C++

```cpp

#include <iostream>

using namespace std;

class Student {

private:

string name;

int age;

public:

// Function to set student details

void setDetails(string n, int a) {

name = n;

age = a;

// Function to display student details

void displayDetails() {

cout << "Name: " << name << ", Age: " << age << endl;

}
2-Functions in C++ - 2030107301

}; 29

int main() {

// Array of 3 Student objects

Student students[3];

// Setting details for each student using setDetails()

students[0].setDetails("Alice", 20);

students[1].setDetails("Bob", 21);

students[2].setDetails("Charlie", 19);

// Displaying details of all students

cout << "Student Details:" << endl;

for (int i = 0; i < 3; i++) {

students[i].displayDetails();

return 0;

Output:

Student Details:

Name: Alice, Age: 20

Name: Bob, Age: 21

Name: Charlie, Age: 19

Explanation:

1. Class Declaration:
2-Functions in C++ - 2030107301

- The `Student` class is defined with two private data members: `name` and `age`. 30

The public member function `setDetails()` sets the values of these members, and
`displayDetails()` displays the student information.

2. Array of Objects:

In the `main()` function, an array `students[3]` is declared to store three objects of type
`Student`.

Each element of the array represents an individual `Student` object.

The details for each student are set using `students[i].setDetails()`, and then the details are
displayed using `students[i].displayDetails()`.

Key Points:

Array of Objects: Instead of managing each object separately, we use an array to manage
multiple objects of the same class.

Accessing Array Elements: Objects in the array are accessed using the array index, just like
any other array.

Encapsulation: Data members (like `name` and `age`) are private and accessed via public
member functions.

Use Cases:

Managing a collection of similar objects (like a list of students, employees, or products) using an
array makes it easier to perform operations on multiple objects.

Useful when you need to perform operations on a group of related objects in a loop

Advantages:

Efficiency: Arrays provide a simple and efficient way to store and access multiple objects.

Code Organization: Managing objects using arrays can make the code more organized and
easier to maintain.

What are Static data members and static member function?


Static members (both variables and functions) are shared across all instances of a class. Unlike
regular members, static members are tied to the class itself rather than any specific object of the
class. They can be accessed without creating any object, and their values persist across
different objects of the same class.
2-Functions in C++ - 2030107301

31
1. Static Member Variables:

Static member variables are declared using the `static` keyword within the class but are
initialized outside the class definition.

These variables are common to all objects of the class. If one object modifies the static variable,
all other objects will see the updated value.

Static variables are initialized **only once** and exist throughout the program's lifetime.

Syntax for static member variable:

class ClassName {

static dataType varName; // Declaration of static member variable

};

// Definition and initialization outside the class

dataType ClassName::varName = initialValue;

2. Static Member Functions:

Static member functions are also declared using the `static` keyword.

Static functions can only access static member variables and other static member functions, as
they are not associated with any specific object.

Static member functions can be called using the class name without needing to create an
object.

Syntax for static member function:

class ClassName {

public:

static void functionName() {

// Function code

};

Example: Static Member Variable and Static Member Function Without Constructor

#include <iostream>
2-Functions in C++ - 2030107301

using namespace std; 32

class Counter {

private:

static int count; // Static member variable

public:

// Static member function to increment the count

static void incrementCount() {

count++;

// Static member function to get the value of count

static int getCount() {

return count;

};

// Initialization of the static member variable outside the class

int Counter::count = 0;

int main() {

// Accessing static member function without creating any object

cout << "Initial Count: " << Counter::getCount() << endl;

// Incrementing the count

Counter::incrementCount();

Counter::incrementCount();

// Getting the updated count value

cout << "Updated Count: " << Counter::getCount() << endl

return 0;

}
2-Functions in C++ - 2030107301

Output: 33

Initial Count: 0

Updated Count: 2

Explanation:

1. Static Member Variable:

The variable `count` is declared as `static` in the class `Counter` and initialized outside the
class with `Counter::count = 0;`.

This static variable is shared by all objects of the `Counter` class, though in this case, no objects
are created.

2. Static Member Function:

The functions `incrementCount()` and `getCount()` are static member functions, meaning they
can be called without needing any object of the class.

These functions operate directly on the static member variable `count`.

3. Accessing Static Members:

Since static members belong to the class and not to objects, we access them using the class
name (e.g., `Counter::getCount()`).

In this example, the `count` variable starts at 0. The static member function `incrementCount()`
is called twice, incrementing `count` by 1 each time.

Finally, `getCount()` is called to display the updated value of `count`.

Key Points:

 Static members** (variables/functions) belong to the class rather than any specific
object.
 Static member functions can only access **static variables** and other static functions.
 They are accessed using the **class name**, not object instances.
 No constructor is required** for static members; they exist and are initialized
independent of object creation.

This feature is particularly useful when a value or function needs to be shared among all
instances of a class or when you need a function that doesn’t depend on object-specific data.

you can pass objects of a class as arguments to functions and also return objects from
functions. This is a powerful feature of object-oriented programming that allows you to
2-Functions in C++ - 2030107301

manipulate objects in functions just like primitive data types. Here, we will discuss how this 34
works without using constructors.

1. Passing Object as an Argument:

An object can be passed to a function by **value**, **reference**, or **pointer**.

When an object is passed **by value**, a copy of the object is made, and any changes made
inside the function won’t affect the original object.

When passed **by reference** or **pointer**, changes made inside the function will affect the
original object.

2. Returning Object from a Function:

- A function can return an object just like any other data type. The function creates and returns
an object to the caller, which can then be used in the calling function.

Example: Passing Object as an Argument and Returning Object

#include <iostream>

using namespace std;

class Box {

public:

int length;

int width;

// Function to set box dimensions

void setDimensions(int l, int w) {

length = l;

width = w;

// Function to display box dimensions


2-Functions in C++ - 2030107301

void displayDimensions() { 35

cout << "Length: " << length << ", Width: " << width << endl;

// A function that takes a Box object as an argument and returns a Box object

Box addDimensions(Box b) {

Box temp;

temp.length = length + b.length;

temp.width = width + b.width;

return temp;

};

int main() {

Box box1, box2, box3;

// Setting dimensions for box1 and box2

box1.setDimensions(10, 5);

box2.setDimensions(20, 10);

// Display dimensions of box1 and box2

cout << "Box 1 Dimensions: ";

box1.displayDimensions();

cout << "Box 2 Dimensions: ";

box2.displayDimensions();

// Passing box2 as an argument to box1's addDimensions method and returning the result

box3 = box1.addDimensions(box2);

// Display dimensions of the new Box (box3)


2-Functions in C++ - 2030107301

cout << "Box 3 (Sum of Box 1 and Box 2) Dimensions: "; 36

box3.displayDimensions();

return 0;

Output:

Box 1 Dimensions: Length: 10, Width: 5

Box 2 Dimensions: Length: 20, Width: 10

Box 3 (Sum of Box 1 and Box 2) Dimensions: Length: 30, Width: 15

Explanation:

1. Class Definition:

The `Box` class has two public data members: `length` and `width`.

There are member functions to set and display the dimensions of a box, and an additional
function `addDimensions` that takes another `Box` object as an argument and returns a new
`Box` object with the summed dimensions.

2. Passing Object as Argument:

The function `addDimensions()` accepts a `Box` object as an argument (`Box b`). Inside the
function, we access the length and width of the passed object and add them to the current
object's dimensions (`length` and `width`).

3. Returning an Object:

Inside the `addDimensions()` function, a temporary `Box` object `temp` is created. The
summed dimensions are stored in `temp`, and then the `temp` object is returned.

This returned object (`box3`) now holds the combined dimensions of `box1` and `box2`.

Key Points:

Object as Argument: An object can be passed as a function argument, either by value (a copy)
or by reference (modifiable original object).
2-Functions in C++ - 2030107301

Returning Object: A function can return an object, allowing you to use objects in expressions 37
or assign them to other objects.

No Constructor Needed: Even without a constructor, the program works by manually setting
the values of the object's attributes using a member function.

No Memory Overhead: The temporary object (`temp`) used to store the result is automatically
destroyed after the function call, thus no additional memory management is required.

This approach is often useful when performing operations that involve multiple objects (such as
adding or modifying the state of one object based on another), and you can do so without
requiring constructors.

What is Scope Resolution Operator?


The **scope resolution operator** (`::`) in C++ is used to **define or access members of a class
or namespace** that are defined outside the class or to resolve ambiguities when there are
multiple identifiers with the same name in different scopes.

Key Uses of the Scope Resolution Operator (`::`):

1. Accessing Global Variables:

If a local variable has the same name as a global variable, the scope resolution operator can
be used to access the global variable.

int x = 10; // Global variable

int main() {

int x = 20; // Local variable

cout << "Local x: " << x << endl;

cout << "Global x: " << ::x << endl; // Access global x using scope resolution operator

return 0;

Output:

Local x: 20

Global x: 10

2. Defining Class Member Functions Outside the Class:

You can declare member functions inside a class and define them outside the class using the
scope resolution operator.
2-Functions in C++ - 2030107301

class MyClass { 38

public:

void display(); // Function declaration

};

// Defining the function outside the class using the scope resolution operator

void MyClass::display() {

cout << "This is a class member function." << endl;

int main() {

MyClass obj;

obj.display(); // Call the function

return 0;

Output:

This is a class member function.

3. Accessing Static Members of a Class:

The scope resolution operator is used to access static members (variables or functions) of a
class.

class MyClass {

public:

static int count; // Static variable declaration

};

// Defining the static variable outside the class using the scope resolution operator

int MyClass::count = 0;

int main() {

cout << "Initial count: " << MyClass::count << endl; // Access static variable

return 0;
2-Functions in C++ - 2030107301

} 39

Output:

Initial count: 0

4. Resolving Ambiguities in Multiple Inheritances:

When a class inherits from multiple base classes, and those base classes have members with
the same name, the scope resolution operator is used to specify which base class's member is
being accessed.

class Base1 {

public:

void display() {

cout << "Base1 display" << endl;

};

class Base2 {

public:

void display() {

cout << "Base2 display" << endl;

};

class Derived : public Base1, public Base2 {

public:

void show() {

Base1::display(); // Using scope resolution to call Base1's display

Base2::display(); // Using scope resolution to call Base2's display

};
2-Functions in C++ - 2030107301

int main() { 40

Derived obj;

obj.show();

return 0;

Output:

Base1 display

Base2 display

5. Accessing Namespace Members:

The scope resolution operator is used to access variables, functions, or classes inside a
namespace.

namespace myNamespace {

int value = 100;

int main() {

cout << "Value from namespace: " << myNamespace::value << endl; // Accessing namespace
variable

return 0;

Output:

Value from namespace: 100

 The **scope resolution operator (`::`)** helps resolve the scope of variables, functions,
and classes.
 It is used for accessing **global variables**, **class static members**, **namespace
members**, and resolving ambiguities in **multiple inheritances**.
 It allows defining **class member functions** outside the class and helps in maintaining
clarity when there are multiple variables or functions with the same name in different
scopes.
2-Functions in C++ - 2030107301

What is friend function?? 41

A **friend function** in C++ is a function that is **not a member** of a class, but is allowed
access to the private and protected members of that class. It is declared inside the class using
the `friend` keyword but is defined outside the class like a normal function.

A friend function can access the private and protected members of the class.

It can be useful in scenarios where you need a function to operate on multiple classes or you
want an external function to access class members.

Example of Friend Function

#include <iostream>

using namespace std;

class Box {

private:

int length; // Private member variable

public:

// Setting the length value using a member function

void setLength(int len) {

length = len;

// Friend function declaration

friend void displayLength(Box obj); // Friend function that can access private members

};

// Friend function definition

void displayLength(Box obj) {

// Friend function can access private members of the class

cout << "The length of the box is: " << obj.length << endl;

int main() {
2-Functions in C++ - 2030107301

Box box1; // Create an object of Box 42

// Set the length of the box using a public member function

box1.setLength(10);

// Call the friend function to display the length

displayLength(box1);

return 0;

Explanation:

1. Class Definition:

 The class `Box` has a private member variable `length` that stores the length of the box.
 The `setLength()` member function is used to assign a value to the `length` variable.
 A friend function `displayLength()` is declared inside the `Box` class with the `friend`
keyword. This function will have access to the private `length` member.

2. Friend Function:

The function `displayLength()` is defined outside the class. Even though it is not a member of
the class, it can access the private member `length` because it is declared as a friend

3. Setting the Value and Displaying It:

The length of the box is set using the public member function `setLength()`, and then the
`displayLength()` friend function is used to display the value of `length`.

4. No Constructor Used:

In this example, we didn't use any constructors. Instead, the length is set using a regular
member function (`setLength`), and the friend function accesses and prints the private member
`length` directly.

Output:

The length of the box is: 10

Key Points:

 A friend function is **not a member** of the class but is allowed to access private and
protected data of the class.
 The friend function is declared inside the class but is defined **outside**.
 In this example, no constructor is used. Instead, the `setLength()` function is used to set
the value of `length`, and the friend function `displayLength()` accesses it.
2-Functions in C++ - 2030107301

43
What is Recursive Function

Recursive is a method in C++ which calls itself directly or indirectly until a suitable
condition is met. In this method, we repeatedly call the function within the same function,
and it has a base case and a recursive condition. he recursive condition helps in the
repetition of code again and again, and the base case helps in the termination of the
condition.

If there is no base case in the recursive function, the recursive function will continue to
repeat continuously.

Here, n==0 is the base case that will terminate the iteration of function when n
becomes equal to zero.

return(n-1) is the recursive function that will help in the repetition of code.

Why Do We Need Recursion?

Recursion can be used in almost every problem, but there are some cases
where the recursion is actually helpful. It is generally used when dealing with
complex
2-Functions in C++ - 2030107301

problems and problems that form a hierarchical pattern; it solves the original 44
problem via the smaller subproblems.

Working of Recursion

Recursion performs a number of repetitive calls to the function from within the function.
The recursive condition performs the repeating calls to the function until the base case
is met.The base case is present inside the function, and once the condition of the base
case is satisfied, it stops the execution.
2-Functions in C++ - 2030107301

In the factorial function, we have to perform many repetitive calls to the function. 45
In this example, the recursive condition would be n*factorial(n-1); factorial is the
function's name, and the value of n is 5.

First, in this function, 5 will be multiplied with factorial(5-1), then 4 is passed to


the function. Similarly, in the next iteration, 4 is multiplied with factorial(4-1). This
will continue till the value of n becomes 1.

Explain Call by Value and Call by Reference and mention what is the difference inboth?

Call by value and Call by Reference are two ways to pass arguments to functions. They
determine how the function accesses and modifies the arguments provided.

Call by Value

Definition: When you pass arguments to a function by value, a copy of the actual value is made
and passed to the function. Changes made to the parameter inside the function do not affect the
original argument.

Example:

void modify(int x) {

x = x + 10; // Only modifies the local copy

}
2-Functions in C++ - 2030107301

46
int main() {

int a = 5;

modify(a); // Passes a copy of a

// a is still 5 here

Usage: This method is generally safer because the original data cannot be modified
accidentally.

Call by Reference

Definition: When you pass arguments to a function by reference, the function receives a
reference (or address) to the original variable. Any changes made to the parameter affect the
original argument.

Example:

void modify(int &x) { // Notice the & symbol

x = x + 10; // Modifies the original variable

int main() {

int a = 5;

modify(a); // Passes a reference to a

// a is now 15 here

Usage: This method is useful when you want to modify the original data or when passing large
data structures to avoid the overhead of copying.

Summary

Call by Value: Copies the value; original remains unchanged.

Call by Reference: Passes the address; original can be modified.


2-Functions in C++ - 2030107301

Call By Value Call by Reference 47

Declaration——> int x; Declaration int &x

A copy of actual argument is Actual argument is passed to the


passed to the function function

Function receives a copy of the Function receives the reference to


original value but not the original the original value.
value .

Actual value does not change Changes made to the formal


parameters affects the actual
value

Actual parameters may be Actual parameter must be


constant variable or expression variable

It works as read only type. It works as read write

Eg void add(int x); Eg void add(int & x)

{x=x+1;} { x=x+1;

Cout << x Int a=5;

Same value 5 Add(5);

Cout <<a;

Output 6

Pointers to members
Pointers to members are used to store the address of a non-static class member (either a data
member or a member function).

These pointers allow indirect access to class members, making them a powerful feature in
scenarios where you want to dynamically bind a class member or function.
2-Functions in C++ - 2030107301

1. Pointer to Data Members 48

A pointer to a data member allows you to store the address of a specific class member.
However, unlike normal pointers, you must also provide an object to access the actual data
since the pointer only points to a member of the class, not the object itself.

Syntax for Pointer to Data Member:

class ClassName {

public:

int data; // Data member

};

int ClassName::*pointerToData; // Declare a pointer to a data member of type int

Example: Pointer to Data Members

#include <iostream>

using namespace std;

class MyClass {

public:

int x;

int y;

};

int main() {

MyClass obj;

obj.x = 10;

obj.y = 20;

// Declare a pointer to the int data member of MyClass


2-Functions in C++ - 2030107301

int MyClass::*ptr = &MyClass::x; // Points to the 'x' data member 49

// Access 'x' using the object and the pointer to member

cout << "Value of x using pointer to member: " << obj.*ptr << endl;

// Change pointer to point to 'y'

ptr = &MyClass::y;

// Access 'y' using the object and pointer to member

cout << "Value of y using pointer to member: " << obj.*ptr << endl;

return 0;

Output:

Value of x using pointer to member: 10

Value of y using pointer to member: 20

Explanation:

1. `int MyClass::*ptr` declares a pointer to an integer data member of `MyClass`.

2. `ptr = &MyClass::x` assigns the address of the member `x` to the pointer.

3. `obj.*ptr` accesses the value of `x` using the object `obj` and the pointer `ptr`.

4. Similarly, you can change the pointer to point to another member, like `y`.

2. Pointer to Member Functions

A pointer to a member function stores the address of a function inside a class. When calling the
function, an object is also needed because the function is specific to a class instance.

Syntax for Pointer to Member Function:

class ClassName {
2-Functions in C++ - 2030107301

public: 50

void memberFunction();

};

// Pointer to a member function

void (ClassName::*pointerToFunction)();

Example: Pointer to Member Functions

#include <iostream>

using namespace std;

class MyClass {

public:

void display() {

cout << "Display function called" << endl;

void show() {

cout << "Show function called" << endl;

};

int main() {

MyClass obj;

// Declare a pointer to the member function of MyClass

void (MyClass::*funcPtr)() = &MyClass::display;


2-Functions in C++ - 2030107301

51
// Call member function using pointer and object

(obj.*funcPtr)(); // Calls the display function

// Change the pointer to point to the show function

funcPtr = &MyClass::show;

(obj.*funcPtr)(); // Calls the show function

return 0;

```

### Output:

Display function called

Show function called

Explanation:

1. `void (MyClass::*funcPtr)()` declares a pointer to a member function that returns `void` and
takes no arguments.

2. The pointer is initialized with the address of the `display()` function using `funcPtr =
&MyClass::display;`.

3. The function is called using `(obj.*funcPtr)();` where `obj` is the object.

4. The pointer is changed to point to `show()` and the function is invoked similarly.

3. Difference Between Regular Pointers and Pointers to Members

Regular pointers store the address of variables or functions that exist independently of any
class.
2-Functions in C++ - 2030107301

Pointers to members store the address of a class member (either a data member or a member 52
function) and require an object or a pointer to an object to be accessed or called.

4. Important Notes:

Pointers to class members are not regular pointers, and they cannot be used directly to access
the member without an instance of the class.

Accessing a member variable or member function via a pointer to a member involves using the
`.*` or `->*` operators depending on whether the object is an instance or a pointer.

Summary:

Pointer to data members: Points to a specific data member of a class. The object instance is
needed to access the value of the member.

Pointer to member functions: Points to a member function of a class. The object instance is
needed to call the member function.

Pointers to members allow for indirect access to the members of a class, making them powerful
in situations where you need dynamic access or have multiple class members you want to
manage through pointers.

************************************************************************************************************

ASSIGNMENT
Q 1: Answer the following Questions (2 Marks)

1. List out types of arguments in c++?

2. Define class and structure.

3. Explain data member and member function of class.

4. What is an Array of Objects?

5. Define Access Specifier.

Q 2: Answer the following Questions (3 Marks)

1. Describe Recursive function with example.

2. Explain Static data member and static member function.

3. Explain Function Prototype with example.

4. Explain :: operator.
2-Functions in C++ - 2030107301

Q 3: Answer the following Questions (5 Marks)


53
1. Explain Call by Value and Call by reference with example.

2. Explain Inline function with example.

3. What is a Friend function? Write a program to calculate the factorial using friend
function.

4. Explain Function Overloading with an example.

5. Write a function name, minimum max that returns the smallest and the largest of three
input values using the parameters, min and max via call by reference

6. Write a function named check() that has three parameters. The first parameter should
accept

7. an integer number, the second parameter floating point number and the third parameter
a

8. double precision number. The body of the function should display the value of the data
passed to the function when it is called.

9. Write a C++ program to overload a function to calculate volume of cube, cylinder and
rectangular box

10. Write inline function to

a. Convert Celsius, temperature to Fahrenheit.

b. Convert Fahrenheit, temperature to Celsius

c. Convert miles to kilometer

d. Convert kilometer to miles

e. Compute the area and volume of a cone of base radius r and height h.

11. What is default argument? Explain all possible scenario of default arguments with
example

***********************************************END********************************************************

You might also like