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