0% found this document useful (0 votes)
4 views33 pages

Unit 3

The document discusses polymorphism in object-oriented programming, highlighting its definition, types (compile-time and runtime), and examples such as function overriding and operator overloading. It explains the rules for operator overloading, data conversion, type casting, and the significance of virtual functions and destructors in ensuring proper memory management. The document provides code examples to illustrate these concepts.

Uploaded by

nayankokane62
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views33 pages

Unit 3

The document discusses polymorphism in object-oriented programming, highlighting its definition, types (compile-time and runtime), and examples such as function overriding and operator overloading. It explains the rules for operator overloading, data conversion, type casting, and the significance of virtual functions and destructors in ensuring proper memory management. The document provides code examples to illustrate these concepts.

Uploaded by

nayankokane62
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Subject :- Object Oriented Programming

Unit 3 ;-
Polymorphism

1. Polymorphism means "many forms", and it occurs Animal


when we have many classes that are related to each animalSo
und()
other by inheritance.

2. Inheritance lets us inherit attributes and methods


from another class. Polymorphism uses those Cats Dogs
animalSo animalSo
methods to perform different tasks. This allows us und() und()
to perform a single action in different ways.
Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism

Two Types of Polymorphism

1. The Memory is allocated at Compile


time in static/compile time memory
allocation
2. The Memory is allocated at Run Time
in Dynamic/Runtime time memory
allocation
Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism

In this example, we have two Compile Time Polymorphism

functions with same name but


different number of arguments. #include <iostream> int main() {
using namespace std; Add obj;
Based on how many parameters we class Add { //This will call the first
public: function
pass during function call determines int sum(int num1, int num2){ cout<<"Output: "<<obj.sum(10,
which function is to be called, this return num1+num2; 20)<<endl;
} //This will call the second
is why it is considered as an int sum(int num1, int num2, function
example of polymorphism because int num3){ cout<<"Output: "<<obj.sum(11, 22,
return num1+num2+num3; 33);
in different conditions the output is } return 0;
}; }
different. Since, the call is
determined during compile time
that's why it is called compile time
polymorphism.
Subject :- Object Oriented Programming
Unit 3 ;-
Function overriding is an example of Polymorphism
Runtime polymorphism.
Function Overriding: When child class Runtime Polymorphism
declares a method, which is already #include <iostream> int main() {
present in the parent class then this is using namespace std; //Parent class object
class A { A obj;
called function overriding, here child public: obj.disp();
class overrides the parent class. void disp(){ //Child class object
In case of function overriding we have cout<<"Super Class B obj2;
Function"<<endl; obj2.disp();
two definitions of the same function, one } return 0;
is parent class and one in child class. The }; }
class B: public A{
call to the function is determined at public:
runtime to decide which definition of void disp(){
the function is to be called, thats the cout<<"Sub Class
Function";
reason it is called runtime }
polymorphism. };
Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism
Operator Overloading

Operator - An operator is a symbol that tells the compiler to perform specific mathematical, logical
manipulations, or some other special operation.

Example:

• arithmetic operator: + , −, ∗, /

• logical operator: && and ||

• pointer operator: & and ∗

• memory management operator: new, delete[ ]


Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism
Operator Overloading
A binary operator is an operator that takes two operands; a unary operator is one
that takes one operands.

Syntax: operand operator operand , a+b

A unary operator is one that takes one operands

Syntax. Operator operand, -a,


Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism
Operator Overloading

Operator overloading refers to the multiple definitions of an operator.

Arithmetic operator such as + and / are already overloaded in C/C++ for different built-in
types.

Example: 2 / 3 // integer division;


result is 0
2.0 / 3.0
// floating-point division; result is 0.666667

For the same operator / , different algorithms are used to compute two types of divisions.
Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism
Operator Overloading

C++ allows most operators to be overloaded for user-defined types(classes).


Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism
Operator Overloading

Operators which cannot be overloaded

1> Scope Resolution Operator (::)


2> Pointer-to-member Operator (.*)
3> Member Access or Dot operator (.)
4> Ternary or Conditional Operator (?:)
5> Object size Operator (sizeof)
6> Object type Operator (typeid)
Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism
Why Operator Overloading?
Overloaded operators have appropriate meaning to user-defined
types, so they can be used for these types.
e.g. to use operator + for adding two objects of a user-defined class.
An operator must be overloaded to be used on class objects
Syntax:
returntype operator +(parameter){ }
Example:
sample operator +(sample obj)
{}
Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism
How to overload operators?
We can overload operators by writing special kinds of functions.
These functions are called operator functions.
To overload operator +,
the name of the operator function is operator+
These operator functions can be:
• class member functions, or
• stand-alone functions.
Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism

Operator Overloading can be done by using three approaches, they are

1. Overloading unary operator.


2. Overloading binary operator.
3. Overloading binary operator using a friend function.
Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism

Below are some criteria/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 = () [] ->.
Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism

Overloading Unary Operator: Let us consider to overload (-) 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.
Example:-
Assume that class Distance takes two member variable i.e. feet and inches, create
a function by which Distance object should increment the value of feet and inches
by 1 (having single operand of Distance Type).
Overload unary + operator
Unary Operator
● Increment (++) Unary operator.
● Decrement (--) Unary operator.
● The minus (-) unary.
● The logical not (!) operator.
Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism
Overloading Unary Operator
The unary operators operate on a single operand and following are the examples
of Unary operators −
● The increment (++) and decrement (--) operators.
● The unary minus (-) operator.
● The logical not (!) operator.
The unary operators operate on the object for which they were called and normally,
this operator appears on the left side of the object, as in !obj, -obj, and ++obj but
sometime they can be used as postfix as well like obj++ or obj--.
Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism
Operator Overloading in Binary Operators
Binary operators work on two operands. For example,

result = num1 + num2;

Here, + is a binary operator that works on the operands num1 and num2.
When we overload the binary operator for user-defined types by using the code:
obj3 = obj1 + obj2;

The operator function is called using the obj1 object and obj2 is passed as an argument
to the function.
Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism
Rules of Operator Overloading
1. The first and basic rule of operator overloading is: we can overload unary operator as only unary
operator, it cannot be overload as binary operator and vice versa.
2. We cannot overload those operators that are not a part of C++ language like ‘$’.
3. We can perform operator overloading in only user defined data types. We cannot change the
operators existing functionality.
4. Using operator overloading we cannot change the presidency and associativity of operators.
5. There are some operators cannot be overloaded that are given below:
○ :: Scope resolution operator.
○ . Class membership operator.
○ ?: ternary or conditional operator.
○ .* pointer to member operator.
○ ->* pointer to member operator.
Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism
Data Conversion
The type conversions are automatic only when the data types involved are built-in
/Primitive types.
int m;
float x = 3.14159;
m = x; // convert x to integer before its value is assigned // to m.
For user defined data types, the compiler does not support automatic type
conversions. We must design the conversion routines by ourselves.
Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism
Data Conversion

Different situations of data conversion between incompatible types.


1. Conversion from basic type to class type.
2. Conversion from class type to basic type.
3. Conversion from one class type to another class type.
Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism
Data Conversion
1. Conversion from basic type to class type:-
In this type of conversion the source type is basic type and the destination
type is class type. Means basic data type is converted into the class type.
For example we have class employee and one object of employee ‘emp’ and
suppose we want to assign the employee code of employee ‘emp’ by any
integer variable say ‘Ecode’ then the statement below is the example of the
conversion from basic to class type.

emp(class type) = Ecode(basic type) ;


Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism
Data Conversion
2. Conversion from class type to basic type:-
In this type of conversion the source type is class type and the destination
type is basic type. Means class data type is converted into the basic type.
For example we have class Time and one object of Time class ‘t’ and suppose
we want to assign the total time of object ‘t’ to any integer variable say
‘duration’ then the statement below is the example of the conversion from
class to basic type.

duration= t ; // where, t is object and duration is of basic data type


Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism
Data Conversion

3. Conversion from one class type to another type:-


In this type of conversion the source type is class type and the destination
type is also class type.

Class A int a=10

Class B int b
Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism
Type casting

Type casting (implicit and explicit):-


A type cast is basically a conversion from one type to another. There are two types of type
conversion:
Implicit Type Conversion Also known as ‘automatic type conversion’.
● Done by the compiler on its own, without any external trigger from the user.
● Generally takes place when in an expression more than one data type is present. In such
condition type conversion (type promotion) takes place to avoid lose of data.
● All the data types of the variables are upgraded to the data type of the variable with largest
data type.
Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism
Type casting

Type casting (implicit and explicit):-


Explicit Type Conversion: This process is also called type casting and it is user-defined.
Here the user can typecast the result to make it of a particular data type.
● Converting by assignment: This is done by explicitly defining the required type in front
of the expression in parenthesis. This can be also considered as forceful casting.
Syntax:(type) expression
where type indicates the data type to which the final result is converted.
Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism
Type casting

// C++ program to demonstrate


// explicit type casting

#include <iostream>
using namespace std;

int main()
{
double x = 1.2;

// Explicit conversion from double to int


int sum = (int)x + 1;

cout << "Sum = " << sum;

return 0;
}
Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism

Explicit Keyword:-

It stops the compiler from doing an implicit conversion


Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism
Virtual Function in C++
A virtual function is a member function which is declared within a base class and is

re-defined(Overriden) by a derived class. When you refer to a derived class object using a pointer

or a reference to the base class, you can call a virtual function for that object and execute the

derived class’s version of the function.

● Virtual functions ensure that the correct function is called for an object, regardless of the
type of reference (or pointer) used for function call.
● They are mainly used to achieve Runtime polymorphism
● Functions are declared with a virtual keyword in base class.
● The resolving of function call is done at Run-time.
Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism
Virtual Function in C++
Rules for Virtual Functions

1. Virtual functions cannot be static and also cannot be a friend function of another class.
2. Virtual functions should be accessed using pointer or reference of base class type to
achieve run time polymorphism.
3. The prototype of virtual functions should be same in base as well as derived class.
4. They are always defined in base class and overridden in derived class. It is not
mandatory for derived class to override (or re-define the virtual function), in that case
base class version of function is used.
5. A class may have virtual destructor but it cannot have a virtual constructor.
Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism
Virtual Destructor
● Deleting a derived class object using a pointer of base class type that has
a non-virtual destructor results in undefined behavior. To correct this
situation, the base class should be defined with a virtual destructor.
Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism

// CPP program without virtual destructor


// causing undefined behavior int main(void)
#include<iostream> {
base *b;
using namespace std; derived d ;
*b=&d;
class base {
public: delete b;
base() getchar();
{ cout<<"Constructing base \n"; } return 0;
~base() }
{ cout<<"Destructing base \n"; }
};

class derived: public base {


public:
derived()
{ cout<<"Constructing derived \n"; }
~derived()
{ cout<<"Destructing derived \n"; }
};
Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism

Making base class destructor virtual guarantees that the object of


derived class is destructed properly, i.e., both base class and derived
class destructors are called. For example,
Subject :- Object Oriented Programming
Unit 3 ;-
Polymorphism
// A program with virtual destructor int main(void)
#include<iostream> {
derived *d = new derived();
using namespace std; base *b = d;
delete b;
class base { getchar();
public: return 0;
base() }
{ cout<<"Constructing base \n"; }
virtual ~base()
{ cout<<"Destructing base \n"; }
};

class derived: public base {


public:
derived()
{ cout<<"Constructing derived \n"; }
~derived()
{ cout<<"Destructing derived \n"; }
};

You might also like