2. Functions
Self contained block of statements which performs a particular task and
returns a value.
The function contains the set of programming statements enclosed by {}.
Collection of functions creates a C/C++ program i.e
C/C++ = main() + add() + sum() + ….. +last()
Function also called module, block, partition, procedure, subroutine
Every C++ program must have the main()
Check the role of main() [ 2 main / key roles ]
3. Importance of functions in a program
Facilitate code Re-use
Facilitate program expansion
Facilitate the location and isolation of faulty functions in a program
Facilitate top down programming
4. Types of functions
1. Library Functions: Functions which are
declared in the C++ header files such as ceil(x),
cos(x), exp(x), gets(), puts(), ceil(), floor(),
sqrt(), pow() etc.
Functions which have been coded, compiled
and utilized in other programs.
2. User-defined functions: Functions which are
created by the C++ programmer, so that he/she
can use it many times. It reduces the
complexity of a big program and optimizes the
code.
Eg addition(), tarus(), a(), sum();
5. Communication in functions
Functions communicate by passing messages.
Three concepts in functions that are very important:
Function declaration
Function call
Function definition
User defined functions must be declared before they are used in the
program.
6. Program demo for functions in C++
/* functions demo program */
#include<stdio.h>
void japan(); //function declaration
void china();
int main()
{
cout<<“n initially in main functionn”;
japan(); function call
cout<<“nfrom japan n”;
china(); function call
cout<<“nfrom china n”;
return 0;
}
void china() //function definition
{
cout<<“n iam in china n”;
}
void japan() //function definition
{
cout“n iam in japan n”;
}
7. Concepts of functions
1. Function Declaration:
Done outside all other functions [ between header files and main() ]
Done inside the class to provide encapsulation.
Syntax:
return_type function_name(return_type1 arg1, ……);
E.g, int addition(int a, int b, int c); parameter /argument
Declaration informs the compiler about the following:
Return type of the function
Function name
Return types of parameters in the argument list.
Number of parameters in the argument list
Nb: Declaration creates a template / structure of the function. This structure will
be used to link the function call and function definition.
8. Function call, definition
• addition(a,b,c); call
• structure of function declaration
• void addition(int x, int y, int z) definition
9. #include<iostream.h>
#include<conio.h>
int sum(int , int );
int subtraction(int, int);
int main()
{
int a, b, result;
cout"nEnter two numbers:";
cin>>a>>b;
result = sum(a, b);
subtraction(a,b);
return 0;
int sum(int x, int y)
{
int z;
z = x + y;
cout<<"nThe sum is : ”<<z;
return 0;
}
Int subtraction(int x, int y)
{
sub =x-y;
return sub;
}
12. Pass by value
Call/Pass by value is the process where the copies of the actual parameters
are passed in one to one correspondence to the formal parameters in the
function definition. Therefore, any changes made in the formal parameters do
not affect the actual parameters.
e.g, addition(int a, int b, int c); call
Copies
int addition(int x, int y, int z) definition
Nb: Variables a, b, c are called actual parameters
Variables x, y, z are called formal parameters
13. /* Pass by Value*/
#include<iostream>
#include<conio.h>
int badilisha(int, int);
int main()
{
int a=5, b=7;
cout<<"nOriginal valuesn";
cout<<"na = t”<<a<<endl;
cout<<"b = n”<<b;
badilisha(a,b);
cout<<"nValue after interchangen";
cout<<"na = t“<<a;
cout<<"b = n“<<b<<endl;
return 0;
}
int badilisha(int x, int y)
{
int z;
z = x;
x = y;
y = z;
cout<<"nValues in fun definitin";
cout<<"na = t“<<x;
cout<<"b = n“<<y;
}
14. Pass by reference
Call/Pass by reference is the process where the original values are passed to the
corresponding function definition. Any changes made in the function definition
affects the actual parameters.
eg addition(int &a, int &b, int &c);
int addition(int *x, int *y, int *z)
Pass by reference uses the concept of Pointers:
15. Pointers
Variable which stores the address of another variable.
Pointer variables can be of type i.e, int, float, char, array, function, etc.
Pointers are user defined datatypes
Syntax for declaration:
return type *variable_name;
int *ptr;
char *c;
int a = 5;
16. Advantages / uses of pointers
Reduces the code and improves the performance, it is used to retrieving strings,
trees, etc. and used with arrays, structures, and functions.
We can return multiple values from a function using the pointer.
It makes you able to access any memory location in the computer's memory.
Dynamic memory allocation
C++ language, we can dynamically allocate memory using malloc() and
calloc() functions
Arrays, Functions, and Structures
C++ language pointers are widely used in arrays, functions, and structures.
17. Examples of pointers in a program
#include<iostream>
using namespace std;
int main () {
int var1;
char var2[10];
cout<<" Address of var1 variable: ";
cout<< &var1 <<endl;
cout<< "Address of var2 variable: ";
cout<< &var2 << endl;
return 0;
}
18. int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
cout << "Value of var variable: ";
cout << var << endl;
cout << "Address stored in ip variable: "; // print the address stored in ip pointer
variable
cout << ip << endl;
cout << "Value of *ip variable: "; // access the value at the address available in
pointer
cout << *ip << endl;
return 0;
}
19. Pointer concepts in C++
1. null pointer:
C++ supports null pointer.
A constant with a value of zero defined in several standard libraries
(iostream)
Done at the time of variable declaration.
int main () {
int *ptr = NULL;
cout << "The value of ptr is " << ptr ;
return 0;
}
• 0, signals that the pointer is not intended to
point to an accessible memory location.
• if a pointer contains the null (zero) value, it is
assumed to point to nothing.
20. Pointer concepts in C++
1. Pointer arithmetic:
• Four arithmetic operators that can be used on pointers: ++, --, +, -
• Let ptr be an integer pointer pointing to address 1000. Then ptr++,
• points to loc 1004 cause each time ptr is incremented, it will point to the next integer.
• operation will move the pointer to next memory location without impacting actual value
at the memory location.
• If ptr points to a character whose address is 1000, then above operation will point to the
location 1001 because next character will be available at 1001.
Incrementing /Decrementing a Pointer
const int MAX = 3;
int main () {
int var[MAX] = {10, 100, 200};
int *ptr;
ptr = var; // increm array address in pointer.
//ptr = &var[MAX-1]; for decrem pointer
for (int i = 0; i < MAX; i++/i--) {
cout << "Address of var[" << i << "] =
";
cout << ptr << endl;
cout << "Value of var[" << i << "] = ";
cout << *ptr << endl;
ptr++ /ptr--; // point to the next location
}
21. Pointer concepts in C++
Pointer Comparisons
compared by using relational operators, such as ==, <, and >.
Let p1 and p2 point to variables that are related to each other such as elements of
the same array, then p1 and p2 can be meaningfully compared.
int main () {
int var[MAX] = {10, 100, 200};
int *ptr;
// let us have address of the first
element in pointer.
ptr = var;
int i = 0;
while ( ptr <= &var[MAX - 1] ) {
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
cout << "Value of var[" << i << "] = ";
cout << *ptr << endl;
// point to the previous location
ptr++;
i++; }
22. Pointer concepts in C++
2. Pointer Vs Arrays
const int MAX = 3;
int main () {
int var[MAX] = {10, 100, 200};
int *ptr;
ptr = var; // let us have array address in pointer.
for (int i = 0; i < MAX; i++) {
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
cout << "Value of var[" << i << "] = ";
cout << *ptr << endl;
ptr++; // point to the next location
}
23. 3. Passing Pointers to Functions
int swap(int *x, int *y);
int main()
{
int a=5, b=7;
cout<<"nOriginal valuesn";
cout<<"na = t“<<a;
cout<<"b = n“<<b;
badilisha(&a,&b);
cout<<"nValue after interchangen";
cout<<"na = %dt", a;
cout<<"b = %dn",b;
return 0; }
int badilisha(int *x, int *y)
{
int z;
z = *x;
*x = *y;
*y = z;
cout<<"nValues in funct definitionn";
cout<<"na = t“<<*x;
cout<<"b = n“<<*y;
}
24. Difference between call by value and call by reference
Call/Pass by value
A copy of value is passed to the
function
Changes made inside the function is
not reflected on other functions
Actual and formal arguments will be
created in different memory location
Call/Pass by reference
An address of value is passed to the
function
Changes made inside the function is
reflected outside the function also
Actual and formal arguments will be
created in same memory location
25. C++ Function Overriding
If derived class defines same function as defined in its base class, it is known as
function overriding
It is used to achieve runtime polymorphism.
It enables you to provide specific implementation of the function which is
already provided by its base class.
26. class Animal {
public:
void eat(){
cout<<"Eating...";
}
};
class Dog: public Animal
{
public:
void eat()
{
cout<<"Eating bread...";
} };
int main()
{
Dog d;
d.eat();
return 0;
}
27. C++ virtual function
A member function in the base class that you redefine in a derived class.
Declared using the virtual keyword.
Used to tell the compiler to perform dynamic linkage or late binding on the
function.
A 'virtual' is a keyword preceding the normal declaration of a function.
When the function is made virtual, C++ determines which function is to be
invoked at the runtime based on the type of the object pointed by the base class
pointer.
There is a necessity to use the single pointer to refer to all the objects of the
different classes. So, we create the pointer to the base class that refers to all the
derived objects. But, when base class pointer contains the address of the derived
class object, always executes the base class function. This issue can only be
resolved by using the 'virtual' function.
28. Rules of Virtual Function
Virtual functions must be members of some class.
Virtual functions cannot be static members.
They are accessed through object pointers.
They can be a friend of another class.
A virtual function must be defined in the base class, even though it is not used.
The prototypes of a virtual function of the base class and all the derived classes
must be identical. If the two functions with the same name but different
prototypes, C++ will consider them as the overloaded functions.
We cannot have a virtual constructor, but we can have a virtual destructor
Consider the situation when we don't use the virtual keyword.
29. class A {
int x=5;
public:
void display()
{
cout << "Value of x is : " <<x<<endl;
}
};
class B: public A {
int y = 10;
public:
void display()
{
cout << "Value of y is : " <<y<<endl;
}
};
int main()
{
A *a;
B b;
a = &b;
a->display();
//b.display();
return 0;
}
Not virtual function demo program
30. Explanation
*a is the base class pointer.
The pointer can only access the base class members but not the members of the
derived class.
Although C++ permits the base pointer to point to any object derived from the
base class, it cannot directly access the members of the derived class.
Therefore, there is a need for virtual function which allows the base pointer to
access the members of the derived class.
31. C++ virtual function
class A {
public:
virtual void display()
{
cout<<"Base class is invoked";
}
};
class B : public A {
public:
void display()
{
cout <<"Derived Class is invoked";
}
};
int main()
{
A *a; //pointer of base class
B b; //object of derived class
a = &b;
a->display();//Late Binding occurs
}
32. Pure Virtual Function
Not used for performing any task. It only serves as a placeholder.
Function declared in the base class that has no definition relative to the base class.
A class containing the pure virtual function cannot be used to declare the objects
of its own, such classes are known as abstract base classes.
The main objective of the base class is to provide the traits to the derived classes
and to create the base pointer used for achieving the runtime polymorphism.
Syntax:
virtual void display() = 0;
33. class Base
{
public:
virtual void show() = 0;
};
class Derived : public Base
{
public:
void show()
{
cout<<"Derived class is derived from the
base class.";
}
};
int main()
{
Base *bptr; //Base b;
Derived d;
bptr = &d;
bptr->show();
return 0;
}
Base class contains the pure virtual function (abstract base class).
We cannot create the object of the base class.
34. Inline function
Functions which are expanded with the keyword inline
Syntax:
inline return_type function_name(parameters)
{
// function code?
}
Importance of inline functions:
to save memory space.
Increase the execution speed
35. Instances where inline functions may not work
If a function is recursive.
If a function contains a loop like for, while, do-while loop.
If a function contains static variables.
If a function contains a switch or go to statement
36. Advantages of inline function
In the inline function, we do not need to call a function, so it does not cause any
overhead.
It also saves the overhead of the return statement from a function.
It does not require any stack on which we can push or pop the variables as it
does not perform any function calling.
An inline function is mainly beneficial for the embedded systems as it yields less
code than a normal function.
Nb: discuss the disadvantages of inline functions
37. Friend Function
A function of the class defined outside the class scope but it has the right to
access all the private and protected members of the class.
friend functions appear in the class definition but friends are the member
functions.
Characteristics of a Friend function:
The friend function is declared using friend keyword.
It is not a member of the class but it is a friend of the class.
As it is not a member of the class so it can be defined like a normal function.
Friend functions do not access the class data members directly but they pass an
object as an argument.
It is like a normal function.
If we want to share the multiple class's data in a function then we can use the
friend function.
38. Reasons for using friend functions
Used when the class private data needs to be accessed directly without using
object of that class.
Used to perform operator overloading.
Syntax:
class class_name
{
friend data_type function_name(argument/s);
};
Function can be defined anywhere in the program like a normal C++
Function definition does not use either the keyword friend or :: operator
Preceded by the keyword friend.
39. Friend class program
class A {
int x =5;
friend class B; // friend class.
};
class B
{
public:
void display(A &a)
{
cout<<"value of x is : "<<a.x;
}
};
int main()
{
A a;
B b;
b.display(a);
return 0;
}
40. Friend function program
class Distance {
private:
int meters;
public:
Distance() // constructor
{
meters = 0;
}
void display_data()
{
cout << "Meters value: "<<meters<<endl;
}
friend void addvalue(Distance &d);
};
void addvalue(Distance &d) // argument
contain the reference
{
d.meters = d.meters+10; //
incrementing the value of meters by 10.
}
int main()
{
Distance d1;
d1.display_data(); // meters = 0
addvalue(d1); // calling friend function
d1.display_data(); // meters = 10
return 0;
}
41. C++ Polymorphism
• The process of using a function or an operator for more than one purpose.
• Having many forms.
• Two types of
polymorphism in C++:
Two types:
Compile time polymo
Runtime polymo
42. Compile time polymorphism:
Overloaded functions are invoked by matching the type and number of arguments.
This information is available at the compile time and, therefore, compiler selects the
appropriate function at the compile time.
achieved by function overloading and operator overloading which is also known as
static binding or early binding.
Run time polymorphism:
achieved when the object's method is invoked at the run.
Achieved by method overriding (also known as dynamic binding or late binding).
43. Static Members of a C++ Class
Class members can be defined using static keyword.
Static declaration of class members means no matter how many objects of the
class are created, there is only one copy of the static member.
A static member is shared by all objects of the class.
All static data is initialized to zero when the first object is created if no other
initialization is present.
Can be initialized outside the class i.e, int Box::objectCount = 0;
44. //static data member
class Box {
public:
static int objectCount;
int display();
// Constructor definition
Box(double l, double b, double h) {
cout <<"Constructor called." << endl;
length = l; breadth = b; height = h;
// Increase every time object is created
objectCount++;
}
double Volume() {
cout<<"n AREA = "<<(length*breadth* height);
}
private:
double length; double breadth; doubl
height;};
// Initialize static member of class Box
int Box::objectCount = 0;
int main(void) {
Box Box1(3.3, 1.2, 1.5);
Box Box2(8.5, 6.0, 2.0);
Box1.Volume();
Box2.Volume();
// Print total number of objects.
cout<<"Tot object:"<<Box::objectCount;
return 0;
}
45. Static Member Function
Functions declared with the keyword static
Function which can be called even if no objects of the class exist, therefore can be
accessed using only the class name and the scope resolution operator ::.
Can only access static data member, other static member functions and any other
functions from outside the class.
Have a class scope.
Do not have access to the this pointer of the class.
Used to determine whether some objects of the class have been created or not.
Properties:
Can only access other static variables or functions present in the same class
Called using the class name. Syntax- class_name::function_name( )
46. class Box {
public:
static int objectCount;
Box(double l, double b, double h) {
cout<<"Constructor called."<<endl;
length = l; breadth = b; height = h;
// Increase every time object is created
objectCount++;
}
double Volume() {
cout<<"nAREA="<<(length*breadth*height);
}
static int getCount() {
return objectCount;
}
private:
double length, breadth, height; };
int Box::objectCount = 0;
int main() {
// Print total number of objects before
creating object.
cout << "Inital Stage Count: "<<
Box::getCount() << endl;
Box Box1(3.3, 1.2, 1.5);
Box Box2(8.5, 6.0, 2.0);
Box1.Volume();
Box2.Volume();
// Print total number of objects after
creating object.
cout << "Final Stage Count: " <<
Box::getCount() << endl;
return 0;
}
47. C++ Math Functions
Trignometric functions: (tan(x), acos(x), sin(x), cos(x))
Hyperbolic functions: (cosh(x), sinh(x), tanh(x), acosh(x))
Exponential functions: (exp(x), log10(x), log(x))
Maximum, Minimum and Difference functions: (fdim(x,y), fmax(x,y), fmin())
Power functions: (pow(x,y), sqrt(x), cbrt(x), hypot(x,y))
48. C++ this Pointer
this is a keyword that refers to the current instance of the class.
Three main usage of this keyword in C++.
It can be used to pass current object as a parameter to another method.
It can be used to refer current class instance variable.
It can be used to declare indexers.
49. class Employee {
public:
int id; //data member (also instance variable)
string name; //data member(also instance
variable)
float salary;
Employee(int id, string name, float salary)
{
this->id = id;
this->name = name;
this->salary = salary;
}
void display()
{
cout<<id<<" "<<name<<"
"<<salary<<endl;
}
};
int main()
{
Employee e1 =Employee(101,
"Sonoo", 890000); //creating an
object of Employee
Employee e2=Employee(102,
"Nakul", 59000); //creating an
object of Employee
e1.display();
e2.display();
return 0;
}
50. Function overloading
Feature that allows us to have more than one function having same name but
different parameter list
Multiple functions can have the same name as long as the number and/or type of
parameters are different.
Advantages:
It increases the readability of
the program because you don't need
to use different names for the same action.
Types of overloading in C++ are:
Function overloading
Operator overloading
51. int mul(int,int);
float mul(float,int);
int mul(int a,int b)
{
return a*b;
}
float mul(double x, int y)
{
return x*y;
}
int main()
{
int r1 = mul(6,7);
float r2 = mul(0.2,3);
cout<< "r1 is : " <<r1<<endl;
cout<<"r2 is : " <<r2<<endl;
return 0;
}