20cs204 Class 3 Pp-II

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 65

SRI RAMAKRISHNA ENGINEERING COLLEGE

VATTAMALAIPALAYAM, N.G.G.O. COLONY POST,


COIMBATORE – 641 022

20CS204
Programming Paradigm-II

CLASS 3
Date:11.08.2021
Why we need functions in C
Functions are used because of following reasons –
To improve the readability of code.
Improves the reusability of the code, same function can be
used in any program rather than writing the same code
from scratch.
Debugging of the code would be easier if you use
functions, as errors are easy to be traced.
Reduces the size of the code, duplicate set of statements
are replaced by function calls.
Declaring, Defining and Calling a Function
Parameter Passing to functions
Calling a Function
Functions are called by their names. If the function is without
argument, it can be called directly using its name. But for
functions with arguments, we have two ways to call them,
Call by Value
In this calling technique we pass the values of arguments which
are stored or copied into the formal parameters of functions.
Hence, the original values are unchanged only the parameters
inside function changes.
Call by reference in C++
In call by reference, original value is modified because we
pass reference (address).
Here, address of the value is passed in the function, so actual
and formal arguments share the same address space. Hence,
value changed inside the function, is reflected inside as well
as outside the function.
Call by Value Diff Call by Reference
Inline Functions in C++
Drawbacks in function:
To save some memory space which becomes when a function
is likely called many times.
Every time a function is called ,it takes a lot of extra time in
executing a series of instructions for tasks such as jumping to
the function, saving registers, pushing arguments into stack
and returning to the calling function.
Diff Normal and Inline Function
Syntax

inline return_type function_name( arguments )


{
// BODY OF THE FUNCTION
}
Example
#include <iostream>
using namespace std;
inline int min(int n1, int n2)
{
return (n1 < n2)? n1 : n2;
}
int main()
{
cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;
cout << "The minimum number out of 37 and 73 is: "<< min(37,73)<<endl;
cout << "The minimum number out of 54 and 9 is: "<< min(54,9)<<endl;
cout << "The minimum number out of 131 and 14 is: "<< min(131,14)<<endl;
cout << "The minimum number out of 9 and 32 is: "<< min(9,32)<<endl;
return 0;
}
Inline With Classes
#include<iostream.h> void main() {
#include<conio.h> line obj;
class line { float val1, val2;
public: clrscr();
inline float mul(float x, float y) cout << "Enter two values:";
{ cin >> val1>>val2;
return (x * y); cout << "\nMultiplication value is:" <<
} obj.mul(val1, val2);
inline float cube(float x) { cout << "\n\nCube value is :" <<
return (x * x * x); obj.cube(val1) << "\t" << obj.cube(val2);
} getch();
}; }
Enter two values: 5 7
Multiplication Value is: 35
Cube Value is: 25 and 343
Limitations of Inline Functions
 Inline functions do not work if the body of the function
contains any sort of looping or iteration.
 Inline functions do not support the use of switch or goto
statements.
 C++ Inline functions cannot work if the function defined is
recursive in nature.
 No other return type except void is allowed while defining the
inline function.
 The inline function should not contain variables with the
keyword static.
Friend Function in C++

• In programming terminology, a friend function helps you


access the private and protected members of another class in
which it is declared with the keyword ‘friend’.
• It is important to note that in order to use a friend function
and to access the non-public members of a class, we need to
declare it within the body of the class itself.
Friend functions in C++ can be of two types

A Method of another class: When we have more than one class


and we want to access the non-public data members of a
particular class, we declare a friend class.
A Global function: A global friend function allows you to access
all the private and protected members of the class, unlike a
normal friend function that allows you to access only specific
members of the class.
Syntax
class Class_name
{
Access specifiers // private or protected
.
.
friend return_type function_name(argument(s));
.
.
}
Example
class WithFriend wf.i=10; // access to private data member
{ cout << wf.i;
int i; }
public: int main()
friend void fun(); // global function as friend {
}; fun(); //Can be called directly
void fun() }
{
WithFriend wf;

Output
10
Example 2
};
#include<iostream>
float calculate(AreaOfCircle ob)
class AreaOfCircle
{
{
return 3.14 * ob.radius * ob.radius;
int radius;
}
public:
int main()
void get()
{
{
AreaOfCircle object;
std::cout << "Enter the radius of Circle : ";
object.get();
std::cin >> radius;
std::cout<<"\nArea of Circle :
}
"<<calculate(object);
friend float calculate(AreaOfCircle ob);
}

Enter the radius of Circle : 5


Characteristic of Friend Function
The friend function is not in class scope.
It should be declared inside the class with ‘friend’ keyword.
It can be defined anywhere in the program and outside of the class
like a normal function. But friend keyword must not be used in the
function definition.
It is not in class scope. So it cannot be called by objects of the class.
It can be called like a normal function.
Usually, it has class objects as arguments.
It cannot access member variables or functions directly, but can only
be accessed by the help of the objects of the class.
It can be declared with any access specifier and the access specifier
does not have any impact on the friend function.
Overloading in C++
Function Overloading in C++
The concept of function overloading to make the code less
redundant by assigning a similar name to different entities by
giving various sets of parameters or arguments.
In simple words, two or more functions have the same name
but are used for different purposes.
Consider a situation where you want to perform a function
display() to display the value of the “2012” using the same
name for the function ‘display’ and print it in the form of an
integer value and a string.
C++ allows us to overload operators in 3 ways. They are:
Methods
Constructors
Indexed Properties
#include <iostream>
using namespace std; Example
void display ( ) //function with no arguments int main()
{ {
int a = 3; display(); //function call with no arguments
cout << a << endl; display(5); //function call with one integer argument
} display(2.3); //function call with one floating argument
void display (int a ) //function with one integer display(5,4.0); //function call with one integer and one
argument floating arguments
{ return 0;
cout << a << endl; } //end of program
}
void display (double a ) //function with one floating Output
argument
3
{
5
cout << a << endl;
2.3
}
void display(int a, float b) //function with one integer 5,4
and one floating arguments
{
cout<< a << " , " << b << endl;
}
Operator Overloading
Operator overloading is achieved with the help of Classes and
Objects in C++. C++ gives you the provision to re-define
inbuilt operators. In simple words, a C++ programmer can use
operators with user-defined types. The keyword ‘operator’ is
of immense importance when dealing with operator
overloading.
This is how you would declare your own operator:
class_name operator operator_symbol (const class_name&);
Operator Overloading
In C++, we can make operators to work for user defined classes.
This means C++ has the ability to provide the operators with a
special meaning for a data type, this ability is known as
operator overloading.
For example, we can overload an operator ‘+’ in a class like
String so that we can concatenate two strings by just using +.
Operators Cannot be overloaded
Scope operator (::)
Size operator (Sizeof)
member selector(.)
member pointer selector(*)
ternary operator(?:)
List of operators that can be
overloaded
+ & < << += |= new

– | <b>= &= , *= new []

* > <= >= ++ <<= delete

/ >> <b>== != && -> delete []

% -= || %= ^= >>= ()

/= ~ ! ->* [] — ^
Syntax
return_type class_name : : operator op(argument_list)
{
// function body
}
return type- type of value returned by the specified operation
op-operator being overloaded
operator is the keyword
Three approaches of Operator
Overloading
Overloading unary operator.
Overloading binary operator.
Overloading binary operator using a friend function.
Rules to define the operator function
In case of a non-static function, the binary operator should have
only one argument and unary should not have an argument.
In the case of a friend function, the binary operator should have
only two argument and unary should have only one argument.
All the class member object should be public if operator
overloading is implemented.
Operators that cannot be overloaded are . .* :: ?:
Operator cannot be used to overload when declaring that
function as friend function = () [] ->
Overloading Unary Operator
In unary operator function, no arguments should be passed.
It works only with one class objects. It is a overloading of
an operator operating on a single operand.
#include<iostream> void operator--() //Overload Unary Decrement
using namespace std; {
class IncreDecre a--;
{ b--;
int a, b; }
public: void operator++() //Overload Unary Increment
void accept() {
{ a++;
cout<<"\n Enter Two Numbers : \n"; b++;
cout<<" "; }
cin>>a;
cout<<" ";
cin>>b;
}
Example
void display() cout<<"\n\n After Incrementing : ";
{ id.display();
cout<<"\n A : "<<a; return 0;
cout<<"\n B : "<<b; }
}
};

int main()
{
IncreDecre id;
id.accept();
--id;
cout<<"\n After Decrementing : ";
id.display();
++id;
++id;
Fill in the Blanks
class Student int main()
{ {
Student A;
int rollno; ____________________
A.____________(1);
public: cout<< A.getRollno();
int _________________() }
{
return rollno;
}
void setRollno(int i)
{
rollno=i;
}
};
Fill in the Blanks
#include <iostream.h> //Main Function
#include<conio.h>
int main() {
// Object Creation For Class
// Class Declaration __________ obj;

//Get Input Values For Object Varibales


class person { cout << "Enter the Name :";
cin >> obj.___________;
//Access - Specifier
public: cout << "Enter the Number :";
cin >> __________.number;

string name; //Show the Output


cout << obj.name << ": " << obj.number << endl;
int number;
}; getch();
return 0;
}
Simple Class Addition: Add Two Integers
#include <iostream> void read() {
#include<conio.h> //Get Input Values For Object Variables using
cin
cout << "Enter Number 1 :";
using namespace std; cin >> num1;

cout << "Enter Number 2 :";


// Addition Class Declaration cin >> num2;
class AdditionClass { }
void sum() {
private://Access - Specifier
// Calculating sum value and assign in 'result'
//Member Variable Declaration result = num1 + num2;
int num1, num2, result; }

void print() {
public://Access - Specifier //Print the Output using cout
//Member Functions read(),sum() and cout << "Result :" << num1 << " + " << num1 << "
print() Declaration = " << result << endl;
}
};
Main function and Output
int main() {
Simple Class Addition: Add Two Integers In C++
// Object Creation For Class
AdditionClass obj1, obj2; AdditionClass : obj1 Usage
Enter Number 1 :100
cout << "Simple Class Addition : Add Two Integers In C++\n";
Enter Number 2 :200
cout << "\nAdditionClass : obj1 Usage" << endl; Result :100 + 100 = 300
obj1.read();
AdditionClass : obj2 Usage
obj1.sum();
Enter Number 1 :700
obj1.print(); Enter Number 2 :900
cout << "\nAdditionClass : obj2 Usage" << endl; Result :700 + 700 = 1600
obj2.read();
obj2.sum();
obj2.print();
getch();
return 0;
}
Scenario 1
There are 3 sections : A, B, and C
The functions that we need to perform in each class are taking
the attendance, distributing newspapers to students who
subscribed for it, and giving them their final grades
attendance()
newspapers()
grades()

How Will U Create Class For These Three Function


This is how the above task would look like
After using inheritance
THINGS TO KNOW
There are two terms you need to be familiar with in order to
understand inheritance in C++.
Base class – It is also known as a superclass or a parent class.
It is responsible for sharing its properties with its derived
class(es).
Derived class – It is also known as a subclass or a child class.
It is responsible for inheriting some of all of the properties of
the base class(es).
Scenario 2
Consider a group of vehicles
You need to create classes for Bus, Car and Truck.
The methods fuelAmount(), capacity(), applyBrakes() will be
same for all of the three classes. If we create these classes
avoiding inheritance then we have to write all of these
functions in each of the three classes.
After using inheritance
we can simply avoid the duplication of data and increase re-
usability. Look at the below diagram in which the three classes
are inherited from vehicle class:
Single Inheritance
This type of inheritance in C++ happens when the parent class
has only one child class. In other words, this is only one derived
class formed from a base class.
Syntax
class Base
{
// BODY OF THE BASE CLASS
};
class Derived : acess_specifier Base
{
// BODY OF THE DERIVED CLASS
};
Example1
#include<iostream.h> void salary()
#include<conio.h> {
cout<<"Enter employee salary: ";
cin>>e.salary; // access base class data member
class employee cout<<"Employee salary: "<<e.salary;
{ }
};
public:
int salary; void main()
{
};
clrscr();
class developer : public employee developer obj;
{ obj.salary();
getch();
employee e;
}
public:
Example 2
#include <iostream> class Derived : public Base
{
using namespace std; // private by default
class Base int derived_value;
{ public:
void derived_input()
public: {
int base_value; cout<<"Enter the integer value of derived class: ";
void base_input() cin>>derived_value;
}
{ void sum()
cout<<"Enter the integer value of base class: "; {
cin>>base_value; cout << "The sum of the two integer values is: " <<
base_value + derived_value<<endl;
}
}
}; };
Example 2
int main()
{
cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;
Derived d; // Object of the derived class
d.base_input();
d.derived_input();
d.sum();
return 0;
}
Multiple Inheritance
This type of inheritance happens when the child class inherits
its properties from more than one base class. In others, the
derived class inherits properties from multiple base classes.
Syntax
class A // Base class of B
{
// BODY OF THE CLASS A
};
class B // Derived class of A and Base class
{
// BODY OF THE CLASS B
};
class C : acess_specifier A, access_specifier A // Derived class of A and B
{
// BODY OF CLASS C
};
Example
#include<iostream> class B
using namespace std; {
public:
class A int B_value;
{ void B_input()
public: {
cout<<"Enter the integer value of class B: ";
int A_value; cin>>B_value;
void A_input() }
};
{
cout<<"Enter the integer value of class C : public A, public B //C is a derived class from
class A: "; classes A and B
{
cin>>A_value; public:
} void difference()
}; {
cout<<"The difference between the two values is: " <<
A_value - B_value<<endl;
}
};
Example 2
int main()
{
cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;
C c; // c is an Object of derived class C
c.A_input();
c.B_input();
c.difference();
return 0;
}
Hierarchical Inheritance
When multiple child classes inherit their properties from just a
single base class.
Syntax
class A // Base class of B
{
// BODY OF THE PROGRAM
};
class B : access_specifier A // Derived class of A
{
// BODY OF THE PROGRAM
};
class C : access_specifier A // Derived class of A
{
// BODY OF THE PROGRAM
};
class D : access_specifier A // Derived class of A
{
// BODY OF THE PROGRAM
};
Example
#include <iostream> class B : public A // B is derived from A
using namespace std; {
public:
class A
void product()
{ {
cout<<"The Product of the two values is: "<< x * y<<endl;
public:
}
int x, y; };
void A_input()
{
cout<<"Enter two values of class A: ";
cin>>x>>y;
}
};
Example
class C : public A //C is derived from A b.A_input();
{ b.product();
c.A_input();
public: c.division();
void division() return 0;
{ }

cout<<"The Division of the two values is: "<< x / y<<endl;


}
};
int main()
{
cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;
B b; // Object b of derived class B
C c; // Object c of derived class C
Multilevel Inheritance

This type of inheritance is the best way to represent the


transitive nature of inheritance. In multilevel inheritance, a
derived class inherits all its properties from a class that itself
inherits from another class.
Syntax
class A // Base class
{
// BODY OF CLASS A
};
class B : acess_specifier A // Derived class of A
{
// BODY OF CLASS B
};
class C : access_specifier B // Derived from derived class B
{
// BODY OF CLASS C
};
Example
#include <iostream>
using namespace std; class Derived1 : public Base // Derived class of base
class
class Base {
{ public:
public: int derived1_value;
void Derived1_input()
int base_value; {
void Base_input() cout<<"Enter the integer value of first derived class: ";
cin>>derived1_value;
{
}
cout<<"Enter the integer value of base class: "; };
cin>>base_value;
}
};
class Derived2 : public Derived1 // Derived class of Derived1 class
{
// private by deafult
int derived2_value;
public:
void Derived2_input()
{
cout<<"Enter the integer value of the second derived class: ";
cin>>derived2_value;
}
void sum()
{
cout << "The sum of the three intger values is: " << base_value + derived1_value +
derived2_value<<endl;
}
};
int main()
{
cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;
Derived2 d2; // Object d2 of second derived class
d2.Base_input();
d2.Derived1_input();
d2.Derived2_input();
d2.sum();
return 0;
}
Hybrid Inheritance
This type of inheritance essentially combines more than two
forms of inheritance. For instance, when a child class inherits
from multiple base classes all of its parent classes and that child
class itself serves as a base class for 3 of its derived classes.
Syntax
class A
{
// BODY OF THE CLASS A
};
class B : public A
{
// BODY OF THE CLASS A
};
class C
{
// BODY OF THE CLASS A
};
class D : public B, public C
{
// BODY OF THE CLASS A
};
Example
#include <iostream> class C
using namespace std; {
class A public:
{ int C_value;
public: C() //Use of a constructor to initialize C_value
int A_value; {
}; C_value = 40;
class B : public A }
{ };
public:
B() // Use of a constructor to initialize A_value
{
A_value = 20;
}
};
Example
class D : public B, public C // D is derived from class B and class C
{
public:
void product()
{
cout<<"The product of the two integer values is: " << A_value *
C_value<<endl;
}
};
int main()
{
cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;
D d; // Object d of derived class D
d.product();
return 0;
}

You might also like