Home About Content Others
Definition:
poly morphism
multiple
forms
Real world example:
carbon
Home About Content Others
Polymorphism in OOPs:
Types:
Home About Content Others
Compile time
polymorphism:
The overloaded member functions are selected for invoking by matching arguments,
both type and number. This information is known to the compiler at the compile time
and therefore, compiler is able to select the appropriate function for a particular call.
This is called early binding or static linking. Also known as compile time
polymorphism, early binding, simply means that object is bound to its function call at
compile time.
Function overloading:
Home About Content Others
Example Program
Examine the following C++ program that
demonstrates function overloading.
Home About Content Others
Operator overloading:
Operator overloading is a powerful feature in C++ that allows
programmers to redefine the behavior of operators
for user-defined data types (classes).
Syntax:
return_type operator op (arguments)
{
// custom code
}
Home About Content Others
Example Program
Write a program that overloads increment operator to work with user-defined
objects.
Home About Content Others
Runtime polymorphism:
The appropriate member function is selected while the program is running; this is known as
runtime function. It is also called dynamic polymorphism.
Virtual function:
C++ supports mechanism known as virtual function, to achieve runtime polymorphism. It is a
member function that you expect to be redefined in derived classes. By simply writing the
“virtual” keyword before a simple function , the function becomes a virtual function.
Properties of virtual function:
• They are dynamic in nature
• Defined by the keyword “virtual” inside a base class and are always declared with a base class
and overridden in a child class.
• A virtual function is called during Runtime.
Home About Content Others
Syntax of virtual function:
virtual return_data_type function_name (<para list>) {
\\ function body
}
Function over-riding:Function overriding means creating a
new Function overriding means creating a new version of a function in a derived class that has the same
name, return type, and parameters as a function in the base class.
When the function is called using a derived class object, the derived version is used, not the base one.
Home About Content Others
Difference between compile time and run time
polymorphism:
Compile time polymorphism Run time polymorphism
Static binding simply means that an object Dynamic binding means that the selection
is bound its function call at compile time. of the appropriate function is done at run
time.
Faster execution rate, as the compiler Comparatively slower execution rate, as
determines which function to call at the decision of which function to call is
compile-time. made at runtime.
This does not require the use of pointer to This requires the use of pointer to objects.
object.
Not applicable Involves inheritance, where a derived class
overrides a function from its base class.
Multiple functions have the same name but Not applicable
different parameters defined. The compiler
determines which function to call based on
the number and types of arguments.
Home About Content Others
Pointers to
Objects
WHAT ARE POINTERS?
A pointer is variable that is used to store a memory
address. Normally , a variable directly contains a
specific value but pointer contains an address of a
variable that contains a specific value. The reference
operator (&) is used to access the memory address of a
variable and store it in a pointer.
POINTER DECLARATION
The method of declaring a pointer is same as declaring a
simple variable. An asterisk (*) sign is used in the
declaration that indicates that the variable is a pointer
variable.
SYNTAX
The syntax of declaring variable is as follows:
Data_type *var;
Home About Content Others
EXAMPLE
int *p;
The above statement declares a pointer variable ‘P’ . The
data type int indicates that it can stores the memory
address of an integer variable. The data type of pointer
must be same as the data type of variable whose memory
address is to b stored in the pointer.
It is also possible to declare many pointer variables in one
statement as follows:
Float *p1, *p2;
POINTER INITIALIZATION
The process of assigning a memory address to a pointer
at the time of declaration is called pointer initialization.
The pointer can be initialized to any valid memory
address. It can also be initialized to a NULL or 0 value.
SYNTAX EXAMPLE
The syntax to initialize pointer is as follows: Int n = 100;
Data_type *p = &variable Int *p = &n;
Home About Content Others
Example Program
Write a program that inputs a number
in an integer variable. It stores the
address of the variable in a pointer and
then displays the value and address of
the variable.
As shown in a code snippet :
1. The example program declares an integer
variable ‘n’ and an integer pointer ‘ptr’.
2. It inputs a value from the user and stores it in
‘n’.
3. The address of ‘n’ is assigned to the ‘ptr’ using
address of operator.
4. Finally, the value and address of the variable
is displayed.
Home About Content Others
Pointers to
Objects
A pointer can also refer to an object of a class. The member
(data member or member function) of an object can be
accessed through pointers by using the symbol _> . The
symbol is known as member access operator.
Syntax
The syntax to declare the pointer to object is as
follows:
class_name *pointer_variable_name;
The syntax of referencing an object with pointer is
as follows:
ptr _> member_function();
Home About Content Others
Example Program
Write a class with an integer data
member , a function to input and a
function to display it. Creates an object
of the class using pointer and calls its
member function.
As shown in a code snippet :
1. The example program declares a class Test and
a pointer ‘ptr’ of type Test. The pointer can refer
to an object of the class.
2. The ‘new’ operator creates an object in the
memory and stores the address in ‘ptr’.
3. The program then uses the pointer to call the
member functions of the objects being referenced
by the pointer.
4. The symbol _> is used to access the member
of any object through pointer. The use of dot
operator with pointer to access any member is
invalid.
Home About Content Others
Output:
In your program, the keywords new and delete are used to dynamically allocate and deallocate memory for an object of the Test class. Here's a breakdown of how and why they are used:
Home About Content Others
The use of key words new and delete:
In the C++ programming language, new and delete are a
pair of language constructs that perform dynamic memory
allocation, object construction and object destruction.
In the example program:
In example program, the keyword new and delete are used to dynamically allocate
and deallocate memory for an object of the test class, respectively.
Code section using new:
ptr = new Test:
This line allocates memory on the heap for an object of class Test.
ptr is a pointer of type Test and it now points to this dynamically allocated object.
This is necessary when you want to control the lifetime of an object manually or
share the pointer across functions.
Code section using delete:
delete ptr;
This line deallocates the memory which was previously allocated with new.
It is essential to prevent memory leaks. Without this line, the memory allocated to
pointer would not be returned to the system, even though main() ends.
In your program, the keywords new and delete are used to dynamically allocate and deallocate memory for an object of the Test class. Here's a breakdown of how and why they are used:
Home About Content Others
Difference between calling member function by object and by
pointer to the object:
Aspect Using Object Using Pointer to Object
Syntax object.functionName(); pointer->functionName();
Access Operator Used Dot (.) operator Arrow (->) operator
Dereferencing Required No Yes, implicitly done by ->
Object Type Actual instance Address/reference to instance
Null Check Needed Not applicable (object is valid) Yes, should ensure pointer is not null
When you work with dynamic memory or pass
Usage Context When you have a direct object
references
Example obj.display(); ptr->display();
Home About Content Others
Array of
pointers in
C++
WHAT ARE POINTERS?
Pointers in C++ are variables that store the address
of another variable while arrays are the data
structure that stores the data in contiguous memory
locations. In C++, we can manipulate arrays by
using pointers to them. These kinds of pointers that
point to the arrays are called array pointers or
pointers to arrays.
WHAT IS AN ARRAY?
An array is a collection of elements of similar data
types that are stored in contiguous memory
locations. The elements are of the same data type.
The name of the array points to the memory
address of its first element.
Home About Content Others
SYNTAX
data_type* array_name[size];
DECLARATION AND INITIALIZATION
1. Array of Pointers to Basic Types
int* ptrArray[5]; // Array of 5 integer pointers
2. Array of Pointers to Objects
class MyClass {// class definition};
MyClass* objPtrArray[10];
// Array of 10 pointers to MyClass objects
3. Dynamic Allocation
int *dynamicPtrs[5];for(int i = 0; i < 5; i++) {
dynamicPtrs[i] = new int(i * 10); // Allocate memory
on heap}
Home About Content Others
Example Program
Create a class named ShopItem having
a setData and getData function to get
and display ID and Price of an item
present in shop and then point the
values by using pointer arrays
As shown in a code snippet 1,
1.We created a class “ShopItem”, which contains
two private data members “id” and “price”.
2.The class “ShopItem” contains two member
functions “setdata” and “getdata”
3.The Function “setdata” will take two parameters
and assign the values of parameters to the
private data members “id” and “price”
4.The Function “getdata” will print the values of
private data members “id” and “price”
Home About Content Others
Example Program
Create a class named ShopItem having
a setData and getData function to get
and display ID and Price of an item
present in shop and then point the
values by using pointer arrays
As shown in code snippet 2,
1.We created an integer variable “size” and assigned the value “3” to
it.
2.Array of objects of size “3” is created dynamically by using the
“new” keyword and its address is assigned to the pointer “ptr”
3.The address of pointer “ptr” is assigned to another pointer
“ptrTemp”
4.Two integer variables “p” and “i” are declared and one float variable
”q” is declared
5.We created a “for” loop which will run till the size of array and will
take input for “id” and “price” from user at run time. In this “for”
loop “setdata” function is called using pointer “ptr”; the function will
set the values of “id” and “price” which user will enter. The value of
the pointer “ptr” is incremented by 1 in every iteration of loop.
6.We created another “for” loop which will run till the size of array
and will print the number of the item. In this “for” loop “getdata”
function is called using pointer “ptr”; the function will print the
values of “id” and “price”. The value of the pointer “ptrTemp” is
incremented by 1 in every iteration of loop.
Home About Content Others
Input Output:
:
Home About Content Others
Types of
Arrays
STATIC ARRAY
In this type of array, memory is allocated at compile time
having a fixed size of it. We cannot alter or update the size
of this array.
Syntax
int a[5] = {1, 2, 3, 4, 5}; //Static Integer Array
• The size is determined automatically based on the
number of values provided during initialization (in this
case, 5).
• The memory is allocated on the stack.
• The size of the array is fixed once it is defined.
Home About Content Others
Types of
Arrays
DYNAMIC ARRAY
IIn this type of array, memory is allocated at run time but not
having a fixed size. Suppose, a user wants to declare any random
size of an array, then we will not use a static array, instead of that
a dynamic array is used in hand. It is used to specify the size of it
during the run time of any program.
Syntax
int *a = new int[5]; //Dynamic Integer Array
• The memory is allocated during the run time by using the new
keyword.
• The size is specified explicitly (in this case, 5).
• The memory is allocated on the heap (not the stack).
• We can change the size of the array later by using delete[ ]
which is used to to deallocate the memory and allocating a new
block with a different size if desired.
Home About Content Others
Types of
Arrays
EXAMPLE OF STATIC ARRAY: INT A[5] = {1, 2, 3, 4, 5};
• A static integer array named a and initializes with the
values 1, 2, 3, 4, and 5.
• The size of this array is determined automatically based
on the number of values provided in the initialization
list.
• Thus the array a is allocated on the stack, and its size
cannot be changed once defined.
Home About Content Others
Types of
Arrays
EXAMPLE OF DYNAMIC ARRAY: INT *A = NEW INT[5];
• In this code, we declare a pointer to an integer named a
and it allocates memory in a dynamic fashion for an
integer array of size 5.
• The new keyword here is used for dynamic memory
allocation, and int[5] specifies the size of this dynamic
array.
• The new operator is used to return the address of the
dynamically allocated memory, which is already stored
in the pointer a.
• This array a is allocated on the Heap, and its size can be
modified later if needed.
Home About Content Others
Pointers and
Inheritance
Pointers
A pointer is a variable that stores the memory
address of another variable.
Syntax:
datatype *pointer_name;
Example:
int a = 10;
int *ptr = &a; // ptr stores address of variable a
Home About Content Others
Definition:
In Pointer and polymorphism, we use a pointer of the base class
to refer to objects of derived classes.
This is only effective when the base class has virtual functions.
Then, even if the pointer is of base class type, the correct
function of the derived class gets called at runtime.
Syntax:
class Base {
public:
virtual void show(); // virtual function
};
class Derived : public Base {
public:
void show() override;
};
Base *ptr; // pointer of base class
Derived obj;
ptr = &obj; // pointer stores address of derived object
ptr->show(); // calls Derived's version due to polymorphism
Home About Content Others
Example:
Pointer in Runtime
Polymorphism
Home About Content Others
Example:
Pointer in Runtime
Polymorphism
Output:
Drawing a circle
Drawing a rectangle
Home About Content Others
Step_by_step
method
1. Shape is a base class
with a virtual function draw().
2. Circle and Rectangle inherit from Shape and
override the draw() function.
3. A Shape* pointer (s) is used to point to both
Circle and Rectangle objects.
4. Even though the pointer type is Shape*, the
correct draw() function is called depending on the
actual object it points to.
5. This is polymorphism using pointers.
Home About Content Others
Pointer and
inheritance
in Polymorphism
Pointer have very important capability of storing the
addresses of different object .A pointer can store the
address of object whose type is same as the type of
pointer. It can also store the address of any object that
belong to any child class of the class of pointer. Suppose
there re three classes A,B,and C.The class A is a parent
class whereas B and C are child classes. A pointer ptr of
class A can store the addresses all abjects of A as well as
B and C.
The type of pointer does not change when a pointer of
parent class refers to an abject of child class. That is why
, the pointer always executes the member function of
parent class even if refers to a child object in the memory.
Home About Content Others
SYNTAX
Home About Content Others
Example Program
Create a Base Class A having a function show() and
derive two classes B and C from it also having same
function. Using a pointer ptr point it towards the object
and show inheritance with help of a pointer.
Home About Content Others
Example Program
Create a Base Class A having a function show() and
derive two classes B and C from it also having same
function. Using a pointer ptr point it towards the object
and show inheritance with help of a pointer.
Home About Content Others
Example Program with
Virtual
Create a Base Class A having a function show() and
derive two classes B and C from it also having same
function. Using a pointer ptr pointing towards the object
and show inheritance with help of a pointer.
Home About Content Others
Example Program with
Virtual
Create a Base Class A having a function show() and
derive two classes B and C from it also having same
function. Using a pointer ptr point it towards the object
and show inheritance with help of a pointer.
Home About Content Others
Comparison between one pointers &different pointers
Case Description Can be accessed
One pointer with different objects One pointer points to different objects at Yes, using dereferencing
different times.
Different pointers to different objects Multiple pointers pointing to different Yes
valid objects.
Home About Content Others
One Pointer Used with Different Objects Different Pointers for Each Object
Home About Content Others
THANK YOU
THANK YOU
THANK YOU
Presented By: Amina Shahid, Warda Saleem,
Atifa Sarwar Rana, Sehrish Bano