C++ Function Prototypes Explained
C++ Function Prototypes Explained
Unit 2 1
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.
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.
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.
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.
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:
int main() { 3
greetUser("Alice");
return 0;
}
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;
}
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
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;
}
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:
#include <iostream>
arr[i] = i;
}
2-Functions in C++ - 2030107301
return arr;
int main()
// Function call
delete[] myArray;
return 0;
Output
Array elements: 0 1 2 3 4
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
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.
#include <iostream>
int main() {
int num1 = 5;
int num2 = 3;
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:
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.
return_type
Syntax return_type function_name(parameters); function_name(parameters) { /*
Function body */ }
Parameter Lists the input parameters the function Must match the parameters specified
List accepts, including their data types. in the prototype, including data types.
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.
This substitution is performed by the C++ compiler at compile time. An inline function may
increase efficiency if it is small.
Syntax:
10
Remember, inlining is only a request to the compiler, not a command. The compiler can ignore
the request for inlining.
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.
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.
2. It also saves the overhead of push/pop variables on the stack when a function is called.
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.
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.
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
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
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.
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:
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
17
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.
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:
};
Here, the access specifier defines the level of access to the class’s data members.
Example
class ThisClass {
public:
2-Functions in C++ - 2030107301
};
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.
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.
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()
#include<iostream>
class Person {
2-Functions in C++ - 2030107301
public: 20
// Data members
string name;
int age;
void introduce()
cout << "Hi, my name is " << name << " and I am "
};
int main()
Person person1;
person1.name = "Alice";
person1.age = 30;
person1.introduce();
return 0;
Output
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.
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.
#include <iostream>
class Person {
private:
string Personname;
// Access specifier
public:
// Member Functions()
Personname = name;
void printname()
} 22
};
int main()
Persons obj1;
obj1.setName("Abhi");
obj1.printname();
return 0;
Personname is:Abhi
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,
Then we have to use the scope resolution:: operator along with the class name and
function name.
Example
#include <iostream> 23
class Person {
public:
string Personname;
int id;
void printname();
};
// ::
void Person::printname()
int main()
Person obj1;
obj1.id = 15;
2-Functions in C++ - 2030107301
24
// call printname()
obj1.printname();
// call printid()
obj1.printid();
return 0;
Output:
Person id is: 15
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.).
#include <iostream>
class Student {
private:
string name;
public:
name = n;
void displayDetails() {
cout << marks[i] << " "; // Displaying marks from the array
};
int main() {
Student student1;
student1.setDetails("John", marks);
student1.displayDetails();
return 0;
Explanation:
In the `Student` class, the `marks[5]` array is declared as a private data member. This allows
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
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
Output:
Name: John
Marks: 85 90 78 88 76
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
ClassName objArray[size];
```
```cpp
#include <iostream>
class Student {
private:
string name;
int age;
public:
name = n;
age = a;
void displayDetails() {
cout << "Name: " << name << ", Age: " << age << endl;
}
2-Functions in C++ - 2030107301
}; 29
int main() {
Student students[3];
students[0].setDetails("Alice", 20);
students[1].setDetails("Bob", 21);
students[2].setDetails("Charlie", 19);
students[i].displayDetails();
return 0;
Output:
Student Details:
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`.
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.
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.
class ClassName {
};
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.
class ClassName {
public:
// Function code
};
Example: Static Member Variable and Static Member Function Without Constructor
#include <iostream>
2-Functions in C++ - 2030107301
class Counter {
private:
public:
count++;
return count;
};
int Counter::count = 0;
int main() {
Counter::incrementCount();
Counter::incrementCount();
return 0;
}
2-Functions in C++ - 2030107301
Output: 33
Initial Count: 0
Updated Count: 2
Explanation:
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.
The functions `incrementCount()` and `getCount()` are static member functions, meaning they
can be called without needing any object of the class.
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.
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.
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.
- 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.
#include <iostream>
class Box {
public:
int length;
int width;
length = l;
width = w;
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;
return temp;
};
int main() {
box1.setDimensions(10, 5);
box2.setDimensions(20, 10);
box1.displayDimensions();
box2.displayDimensions();
// Passing box2 as an argument to box1's addDimensions method and returning the result
box3 = box1.addDimensions(box2);
box3.displayDimensions();
return 0;
Output:
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.
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.
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 main() {
cout << "Global x: " << ::x << endl; // Access global x using scope resolution operator
return 0;
Output:
Local x: 20
Global x: 10
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:
};
// Defining the function outside the class using the scope resolution operator
void MyClass::display() {
int main() {
MyClass obj;
return 0;
Output:
The scope resolution operator is used to access static members (variables or functions) of a
class.
class MyClass {
public:
};
// 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
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() {
};
class Base2 {
public:
void display() {
};
public:
void show() {
};
2-Functions in C++ - 2030107301
int main() { 40
Derived obj;
obj.show();
return 0;
Output:
Base1 display
Base2 display
The scope resolution operator is used to access variables, functions, or classes inside a
namespace.
namespace myNamespace {
int main() {
cout << "Value from namespace: " << myNamespace::value << endl; // Accessing namespace
variable
return 0;
Output:
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
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.
#include <iostream>
class Box {
private:
public:
length = len;
friend void displayLength(Box obj); // Friend function that can access private members
};
cout << "The length of the box is: " << obj.length << endl;
int main() {
2-Functions in C++ - 2030107301
box1.setLength(10);
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
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:
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.
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.
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) {
}
2-Functions in C++ - 2030107301
46
int main() {
int a = 5;
// 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:
int main() {
int a = 5;
// 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
{x=x+1;} { x=x+1;
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
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.
class ClassName {
public:
};
#include <iostream>
class MyClass {
public:
int x;
int y;
};
int main() {
MyClass obj;
obj.x = 10;
obj.y = 20;
cout << "Value of x using pointer to member: " << obj.*ptr << endl;
ptr = &MyClass::y;
cout << "Value of y using pointer to member: " << obj.*ptr << endl;
return 0;
Output:
Explanation:
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`.
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.
class ClassName {
2-Functions in C++ - 2030107301
public: 50
void memberFunction();
};
void (ClassName::*pointerToFunction)();
#include <iostream>
class MyClass {
public:
void display() {
void show() {
};
int main() {
MyClass obj;
51
// Call member function using pointer and object
funcPtr = &MyClass::show;
return 0;
```
### Output:
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;`.
4. The pointer is changed to point to `show()` and the function is invoked similarly.
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)
4. Explain :: operator.
2-Functions in C++ - 2030107301
3. What is a Friend function? Write a program to calculate the factorial using friend
function.
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
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********************************************************