0% found this document useful (0 votes)
15 views

Unit 3

Uploaded by

yuvrajahuja2003
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Unit 3

Uploaded by

yuvrajahuja2003
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

Unit 3

Polymorphism
 The word polymorphism means having many forms. In simple words, we can
define polymorphism as the ability of a message to be displayed in more than
one form.
 Real life example of polymorphism, a person at the same time can have
different characteristic. Like a man at the same time is a father, a husband,
an employee. So the same person posses different behavior in different
situations. This is called polymorphism.
 Polymorphism is considered as one of the important features of Object
Oriented Programming.
In C++ polymorphism is mainly divided into two types:
 Compile time Polymorphism
 Runtime Polymorphism
Compile time Polymorphism
 This type of polymorphism is achieved by function overloading or operator
overloading.
 When there are multiple functions with the same name but different
parameters, then the functions are said to be overloaded, hence this is known
as Function Overloading.
 Functions can be overloaded by changing the number of arguments or/and
changing the type of arguments.
 In simple terms, it is a feature of object-oriented programming providing
many functions that have the same name but distinct parameters when
numerous tasks are listed under one function name. There are certain Rules
of Function Overloading that should be followed while overloading a function.
Function Overloading
 When there are multiple functions with the same name but different
parameters, then the functions are said to be overloaded, hence this is known
as Function Overloading.
 Functions can be overloaded by changing the number of arguments or/and
changing the type of arguments.
 In simple terms, it is a feature of object-oriented programming providing
many functions that have the same name but distinct parameters when
numerous tasks are listed under one function name.
 There are certain Rules of Function Overloading that should be followed while
overloading a function.
#include <iostream.h>

using namespace std;


class ABC {
public:
// Function with 1 int parameter
void func(int x)
{
cout << "value of x is " << x << endl;
}
// Function with same name but
// 1 double parameter
void func(double x)
{
cout << "value of x is " << x << endl;
}

// Function with same name and


// 2 int parameters
void func(int x, int y)
{
cout << "value of x and y is " << x << ", " << y
<< endl;
}
};
// Driver code
int main()
{
ABC obj1;
// Function being called depends
// on the parameters passed
// func() is called with int value
obj1.func(7);
// func() is called with double value
obj1.func(9.132);
// func() is called with 2 int values
obj1.func(85, 64);
return 0;
}
Output
value of x is 7
value of x is 9.132
value of x and y is 85, 64
Operator Overloading
 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 make use of the addition operator (+) for string class to
concatenate two strings.
 We know that the task of this operator is to add two operands. So a single
operator ‘+’, when placed between integer operands, adds them and when
placed between string operands, concatenates them.
// C++ program to demonstrate
// Operator Overloading or
// Compile-Time Polymorphism
#include <iostream.h>
using namespace std;

class Complex {
private:
int real, imag;

public:
Complex(int r = 0, int i = 0)
{
real = r;
imag = i;
}
// This is automatically called
// when '+' is used with between
// two Complex objects
Complex operator+(Complex const& obj)
{
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};
// Driver code
int main()
{
Complex c1(10, 5), c2(2, 4);

// An example call to "operator+"


Complex c3 = c1 + c2;
c3.print();
}
Output
12 + i9
Overloading Unary Operator
In the unary operator function, no arguments should be passed. It works only
with one class object. It is the overloading of an operator operating on a single
operand.
// C++ program to show unary
// operator overloading
#include <iostream>
using namespace std;
class Distance {
public:
int feet, inch;
// Constructor to initialize
// the object's value
Distance(int f, int i)
{
this->feet = f;
this->inch = i;
}
// Overloading(-) operator to
// perform decrement operation
// of Distance object
void operator-()
{
feet--;
inch--;
cout << "\nFeet & Inches(Decrement): " <<
feet << "'" << inch;
}
};
// Driver Code
int main()
{
Distance d1(8, 9);

// Use (-) unary operator by


// single operand
-d1;
return 0;
}
Output
Feet & Inches(Decrement): 7'8
Overloading Binary Operator
 In the binary operator overloading function, there should be one argument to
be passed. It is the overloading of an operator operating on two operands.
 Below is the C++ program to show the overloading of the binary operator (+)
using a class Distance with two distant objects.
// C++ program to show binary
// operator overloading
#include <iostream>
using namespace std;

class Distance {
public:
int feet, inch;
Distance()
{
this->feet = 0;
this->inch = 0;
}

Distance(int f, int i)
{
this->feet = f;
this->inch = i;
}
// Overloading (+) operator to
// perform addition of two distance
// Call by reference
Distance operator+(Distance& d2)
{
// Create an object to return
Distance d3;
d3.feet = this->feet + d2.feet;
d3.inch = this->inch + d2.inch;

// Return the resulting object


return d3;
}
};
// Driver Code
int main()
{
Distance d1(8, 9);
Distance d2(10, 2);
Distance d3;

// Use overloaded operator


d3 = d1 + d2;

cout << "\nTotal Feet & Inches: " <<


d3.feet << "'" << d3.inch;
return 0;
}
Output
Total Feet & Inches: 18'11
Runtime Polymorphism
 This type of polymorphism is achieved by Function Overriding. Late binding
and dynamic polymorphism are other names for runtime polymorphism.
 The function call is resolved at runtime in runtime polymorphism. In
contrast, with compile time polymorphism, the compiler determines which
function call to bind to the object after deducing it at runtime.
Function Overriding
 This type of polymorphism is achieved by Function Overriding. Late binding
and dynamic polymorphism are other names for runtime polymorphism.
 The function call is resolved at runtime in runtime polymorphism. In contrast,
with compile time polymorphism, the compiler determines which function
call to bind to the object after deducing it at runtime.
Function Overriding
 Function Overriding occurs when a derived class has a definition for one of
the member functions of the base class. That base function is said to be
overridden.
Runtime Polymorphism with Data Members
 Runtime Polymorphism cannot be achieved by data members in C++.
 Let’s see an example where we are accessing the field by reference variable
of parent class which refers to the instance of the derived class.
Example
#include <iostream.h>
using namespace std;
class base
{
public:
virtual void print ()
{ cout<< "print base class" <<endl; }
void show ()
{ cout<< "show base class" <<endl; }
};
class derived:public base
{
public:
void print () //print () is already virtual function in derived class,
//we could also declared as virtual void print () explicitly
{ cout<< "print derived class" <<endl; }
void show ()
{ cout<< "show derived class" <<endl; }
};
//main function
int main()
{
base *bptr;
derived d;
bptr = &d;
//virtual function, binded at runtime (Runtime polymorphism)
bptr->print();
// Non-virtual function, binded at compile time
bptr->show();
return 0;
}
Output
print derived class
show base class
Differences b/w compile time and run time polymorphism
Compile time polymorphism Run time polymorphism
The function to be invoked is known The function to be invoked is known
at the compile time. at the run time.

It is also known as overloading, early It is also known as overriding,


binding and static binding. Dynamic binding and late binding.

Overloading is a compile time Overriding is a run time


polymorphism where more than one polymorphism where more than one
method is having the same name but method is having the same name,
with the different number of number of parameters and the type
parameters or the type of the of the parameters.
parameters.
Differences b/w compile time and run time polymorphism
Compile time polymorphism Run time polymorphism

It is achieved by function It is achieved by virtual functions


overloading and operator and pointers.
overloading.
It provides fast execution as it is It provides slow execution as it is
known at the compile time. known at the run time.

It is less flexible as mainly all the It is more flexible as all the things
things execute at the compile time. execute at the run time.
Pointers
 Pointers to objects in C++, especially, provide powerful capabilities for memory
management, allowing developers to allocate and deallocate memory
dynamically.
 In C++, a pointer is a variable that holds the memory address of another
variable. Pointers allow for efficient memory utilization, as they enable
dynamic memory allocation, deallocation, and indirect access to objects.
 When declaring a pointer, the type of the pointer must match the type of the
variable it will be pointing to.
Pointer variable declaration in C++
datatype *var_name;

int *ptr; // Ptr can direct attention to an address that contains int data.
What Is Pointer To Object In C++?
 A pointer to an object in C++ is a variable that holds the memory address of
an object. It allows indirect access to the object, providing a way to
manipulate and interact with the object dynamically.
 Pointers to objects are particularly useful when dealing with dynamically
allocated memory, enabling flexible memory management and dynamic
object creation.
 In C++, when an object is created, it occupies a specific memory location.
Pointers to objects store the address in memory, where the object is stored
rather than the object itself. By using pointers, programmers can access and
modify the object indirectly through the pointer.
#include <iostream>
class MyClass {
public:
void myFunction() {
std::cout << "Hello from MyClass!" << std::endl;
}
};
int main() {
MyClass obj; // Create an object of MyClass
MyClass* ptr = &obj; // Create a pointer to the object
ptr->myFunction(); // Access functions using the pointer
return 0;
}
Output
Hello from MyClass!

 We first create an object of the class MyClass named obj.


 We then declare a pointer ptr of type MyClass* and assign it the memory
address of obj using the address-of operator (&).
 Through the pointer ptr, we can access the member function myFunction() of
the obj object using the arrow operator (->).
Declaration And Use Of Object Pointers In C++
The process for expressing object pointers is synonymous with that of ordinary
pointers, i.e., appending it to the name of the pointer type. We use the arrow
operator (->) instead of the dot operator when utilizing an object pointer to
access members of an already-defined class.
Advantages Of Pointer To Object In C++
 Pointers grant us the power to dynamically distribute storage, enabling object
creation at execution and releasing memory when it is not needed. It is
especially useful in situations where either the generation of objects is
dependent on user input, or there are other runtime conditions, or when
knowledge of an object's size at compile time is lacking.
 When compared to passing by value, pointers allow us to pass objects to
functions by reference, which can be more effective. When we provide an
object by value, a copy of the item is made, which for large objects can be
time and memory consuming. It is more effective to pass an object by
reference, which merely passes the item's address.
Advantages Of Pointer To Object In C++
 Incorporating polymorphism into our coding is a viable option, as instances of
derived classes can be pointed to by including pointers from their base
equivalents. As long as they share a base class, we can develop code that
interacts with objects of various sorts.
 Smart pointers offer ownership semantics for objects that are allocated
dynamically. Objects' lifespan can be governed using these tools to ensure
they are properly disposed of when no longer necessary. This guarantees
accurate deallocation and prevents any unintended consequences from the
object's persistence.
thisobject
In C++ programming, this is a keyword that refers to the current instance of the
class. There can be 3 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.
#include <iostream>
using namespace std;
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(void) {
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;
}
Output
101 Sonoo 890000
102 Nakul 59000
Virtual Function
A virtual function (also known as virtual methods) is a member function that is
declared within a base class and is re-defined (overridden) 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 method.
 Virtual functions ensure that the correct function is called for an object,
regardless of the type of reference (or pointer) used for the function call.
 They are mainly used to achieve Runtime polymorphism.
 Functions are declared with a virtual keyword in a base class.
 The resolving of a function call is done at runtime.
Rules for Virtual Functions
 Virtual functions cannot be static.
 A virtual function can be a friend function of another class.
 Virtual functions should be accessed using a pointer or reference of base class
type to achieve runtime polymorphism.
 The prototype of virtual functions should be the same in the base as well as
the derived class.
 They are always defined in the base class and overridden in a derived class. It
is not mandatory for the derived class to override (or re-define the virtual
function), in that case, the base class version of the function is used.
 A class may have a virtual destructor but it cannot have a virtual constructor.
#include <iostream>
{
public:
virtual void display()
{
cout << "Base class is invoked"<<endl;
}
};
class B:public A
{
public:
void display()
{
cout << "Derived Class is invoked"<<endl;
}
};
int main()
{
A* a; //pointer of base class
B b; //object of derived class
a = &b;
a->display(); //Late Binding occurs
}
Output
Derived Class is invoked
Pure Virtual Function
 A virtual function is not used for performing any task. It only serves as a
placeholder.
 When the function has no definition, such function is known as "do-nothing"
function.
 The "do-nothing" function is known as a pure virtual function. A pure virtual
function is a 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.
 virtual void display() = 0;
#include <iostream>
using namespace std;
class Base
{
public:
virtual void show() = 0;
};
class Derived : public Base
{
public:
void show()
{
std::cout << "Derived class is derived from the base class." << std::endl;
}
};
int main()
{
Base *bptr;
//Base b;
Derived d;
bptr = &d;
bptr->show();
return 0;
}
Output
Derived class is derived from the base class.

You might also like