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

Polymorphism

The document discusses pointers and polymorphism in C++. It covers concepts like pointers, pointer arithmetic, pointers to objects, and this pointer. Example code is provided to demonstrate arithmetic operations on pointers and using this pointer.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Polymorphism

The document discusses pointers and polymorphism in C++. It covers concepts like pointers, pointer arithmetic, pointers to objects, and this pointer. Example code is provided to demonstrate arithmetic operations on pointers and using this pointer.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

Unit 04 :

Pointers and Polymorphism


in c++

Written by
Unit Outcome 1 : Create C++
programs to perform the given
arithmetic operations using
pointers

Written by
Learning Outcome 1 : student will be
able to use pointers.

Written by
What we will learn today

1. Concept of Pointers Key takeaways


2. Arithmetic operation on pointers Concept of Pointers

Page 4 Maharashtra State Board of Technical Education 4 July 2020


Concept Map

Pointer
Declaration

Working Of
Pointer Pointer
Initialization

Pointer

Memory
Allocation Operation
on Pointer

Page 5 Maharashtra State Board of Technical Education 4 July 2020


Learning Objective/ Key learning

► To use pointer and perform operations on pointers.

► Write program to perform arithmetic operation on pointers.

Page 6 Maharashtra State Board of Technical Education 4 July 2020


Concept Explanation: Pointers

► Every variable is a memory location and every memory location has its address defined
► Address can be accessed using ampersand (&) operator which denotes an address
► C++ tasks are performed more easily with pointers
► C++ tasks, such as dynamic memory allocation, cannot be performed without them
► Pointer is a variable in C++ that holds the address of another variable.
► Pointers have data type just like variables.
► Pointers are variables which display value at the memory address.
► Like any variable or constant, you must declare a pointer before you can work with it
7

Page 7 Maharashtra State Board of Technical Education 4 July 2020


Declaring and initializing pointer
► The variable which store address of integer variable it is called as an integer pointer.

► Similarly if we stores address of character variable it is called as character pointer

► Declaring Pointers
► Syntax:

data_type *pointer_name;
int *ptr; //declaration
8
ptr=&a; //initialization

Page 8 Maharashtra State Board of Technical Education 4 July 2020


C++ Pointer Operators : Reference and Dereference Operators

► Pointer operators used in C++ are :


► ‘value at’ operator
► * is the dereference operator and can be read as “value pointed by”.
► ‘address’ operator
► & is the reference operator and can be read as “address of”.

Pointer Operator

Address Operator Indirection


(&) Operator (*)

Page 9 Maharashtra State Board of Technical Education 4 July 2020


Example By Using Pointer

#include<iostream.h>
void main()
{ ptr a
int a=10;
int *ptr; Value of ptr 1024 10
ptr=&a; 1000 1024
cout<<"\n Value of a:"<<a; //a=10 Value of a

cout<<"\n Value at ptr:"<<*ptr; //*ptr=10


cout<<"\n Address of a:"<<&a; //&a=1024
cout<<"\n Address of a:"<<ptr; //ptr=1024
cout<<"\n Address of ptr:"<<&ptr; //&ptr=1000 Address of Address of ‘a’ (&a)
} ptr

Page 10 Maharashtra State Board of Technical Education 4 July 2020


Pointer Arithmetic

► Operation
► Increment operator (++)
► Decrement operator (–)
► Addition (+)
► Subtraction (-)

► Valid statements
► p2-p1;
► ptr1+1;
► ptr=ptr+2;

► Invalid statements
► p1+p2;
► p2 * p1;
► p2/p1;
Page 11 Maharashtra State Board of Technical Education 4 July 2020
Pointer Arithmetic

► C++ allows pointers to perform some arithmetic operations like :


⮚ A pointer can be incremented (++) or decremented(--).

⮚ Any integer can be added to or subtracted from a pointer.

⮚ One pointer can be subtracted from another.

Page 12 Maharashtra State Board of Technical Education 4 July 2020


Example

► int a=10, b=5;


0000 a
► Assign p1=&a and p2=&b
P1 0001 Value
► So value of p1 will become 0000 (starting address of a) 0002 is 10
► Value of p2 will become 0004 (starting address of b) 0003
0004 b
P2 0005 Value
0006 is 5
► When we perform p1 - p2 0007
► It will not calculate difference of how many bytes fall between the two addresses, but rather how
many elements are there.
► P1+P2 Its not valid as we cannot perform addition of addresses

Page 13 Maharashtra State Board of Technical Education 4 July 2020


Example Of Arithmetic Operation On Pointer

Program code

Output

Page 14 Maharashtra State Board of Technical Education 4 July 2020


What we will learn today

1. Pointer to Object Key takeaways


2. This Pointer Concept Of Pointer To Object

3. Pointer To Derived Class

Page 15 Maharashtra State Board of Technical Education 4 July 2020


Concept Map

Pointer to
Object Pointee derived
class

Pointer This pointer

Page 16 Maharashtra State Board of Technical Education 4 July 2020


Learning Objective/ Key learning

► To use pointer to object.

► To use This pointer.

► Write program using This pointer.

Page 17 Maharashtra State Board of Technical Education 4 July 2020


Concept Explanation: Pointers To Objects

⮚ A pointer can point to an object created by class. ⮚ Syntax:

⮚ Object pointers are useful in creating objects at Class_name * variable name;

run time. Variable_name=&Object_name;

⮚ Object pointers can be used to access public ⮚ Example:

members of an object. Item obj;


Item *ptr;
⮚ We can refer to public member of object using
ptr=&obj;
two ways
obj->getdata();
⮚ dot operator ( . )
obj->putdata();
⮚ arrow operator (->) 18

Page 18 Maharashtra State Board of Technical Education 4 July 2020


Concept Explanation: Pointers To Objects

⮚ As object pointer is an alias of object ⮚ ptr can be used to refer to member


variable, we can also use ptr->getdata();
(*object_pointer).member_function() ⮚ We can also create an array of objects
► We can also create object using pointers using pointers
and new operatora ⮚ item *ptr=new item[10];
► Example: item *ptr=new item; ⮚ This statement creates memory space for
⮚ This statement allocates enough memory an array of 10 objects.
for the data members in the object and
assign address of the memory space to 19

Page 19 ptr. Maharashtra State Board of Technical Education 4 July 2020


This Pointer

► C++ uses a unique keyword called ‘this’ to represent an object that invokes a
member function.
► This unique pointer is automatically passed to a member function when it is invoked.
► ‘this’ is a pointer that always point to the object for which the member function was
called.
► The ‘this’ pointer can be treated like any other pointer to an object.
► For example, the function call
20
A.max () will set the pointer ‘this’ to the address of the object A.
Next time suppose we call B.max(), the pointer ‘this’ will store address of object B.

Page 20 Maharashtra State Board of Technical Education 4 July 2020


Program using This pointer:

If we try to write
x=x;
It will give garbage Value

Output :

Page 21 Maharashtra State Board of Technical Education 4 July 2020


Pointer To Derived Classes

► Pointers can be used to the base class objects ► Example:


as well as objects of derived class. B *cptr; // pointer to B class
B b; //Base object
► Pointers to objects of base class are
D d; // Derived object
compatible with pointers to objects of a cptr=&b; //ptr points to object b
derived class.
► We can make cptr to point to the
► Single pointer variable can be made to point
object d as follows:
objects belonging to different classes.
cptr=&d; //ptr points to object d
► If B is base and D is derived class, then pointer
declared as a pointer to B can also be a pointer

Page 22
to D. Maharashtra State Board of Technical Education 4 July 2020
Pointers to derived class

► Example:
B *cptr; // pointer to B class
B b; //Base object
D d; // Derived object
cptr=&b; //ptr points to object b

► We can make cptr to point to the object d as follows:


► cptr=&d; //ptr points to object d
► Problem is by using cptr to access the public members of the derived class D.
► The pointer cptr can point to both b and d.
► Using cptr, we can access only those members which are inherited from B and not the members that
originally belongs to D.
► If a member of D has the same name as one of the members of B, then any reference to that member
by cptr will always access the base class member.
Page 23 Maharashtra State Board of Technical Education 4 July 2020
Pointer to Derived class

Output :

Page 24 Maharashtra State Board of Technical Education 4 July 2020


Advantages of pointer

► Pointers save the memory.

► Pointers reduce the length and complexity of a program.


► Pointers allow passing of arrays and strings to functions more efficiently.
► Pointers make possible to return more than one value from the function.

► Pointers increase the processing speed.

Page 25 Maharashtra State Board of Technical Education 4 July 2020


Unit Outcome 2 : Use function
overloading to solve the given
problem
Unit Outcome 3 : Use operator
overloading to solve the given
problem

Written by
Learning Outcome 1 : student will be
able to use different types of
Polymorphism

Written by
What we will learn today

1. Introduction to polymorphism Key takeaways


2. Types of polymorphism Concept of polymorphism

Page 28 Maharashtra State Board of Technical Education 4 July 2020


Concept Map

Page 29 Maharashtra State Board of Technical Education 4 July 2020


Learning Objective/ Key learning

► To describe the working of polymorphism.


► Do you know types of polymorphism?

Page 30 Maharashtra State Board of Technical Education 4 July 2020


Concept Explanation: Polymorphism

► Polymorphism is the ability of an object to take on many forms.


► The most common use of polymorphism in OOP occurs when a parent class reference is used to refer
to a child class object.
► Polymorphism can be static or dynamic.

Divide it two parts


POLYMORPHISM

MANY FORMS

31

Page 31 Maharashtra State Board of Technical Education 4 July 2020


Example of Polymorphism

Business
man
Salesman

Family
head

Employee
Polymorphism

32
Customer

Page 32 Maharashtra State Board of Technical Education 4 July 2020


TYPES OF POLYMORPHISM

POLYMORPHISM

COMPILE TIME RUN TIME

FUNCTION OPERATOR 33
VIRTUAL FUNCTION
OVERLOADING OVERLOADING

Page 33 Maharashtra State Board of Technical Education 4 July 2020


COMPILE TIME POLYMORPHISM
#include <iostream>
► In Compile time Polymorphism or static using namespace std;
polymorphism, the response to a function is
void show(int i) {
determined at the compile time.
cout << " Here is int " << i << endl;
► The linking of a function with an object during }
compile time is called early binding or static void show(double f) {
cout << " Here is float " << f << endl;
binding.
}
► The compile time polymorphism is achieved by int main() {
function overloading and operator overloading. show(20);
show(40.5);
return 0;
}

Page 34 Maharashtra State Board of Technical Education 4 July 2020


RUN TIME POLYMORPHISM

class base
► Runtime polymorphism or Dynamic Method
{
Dispatch is a process in which a call to an public:
void show ()
overridden method is resolved at runtime rather { cout<< "show base class" ;}
};
than compile-time.

class derived:public base


► The run time polymorphism is achieved by
{
Function overriding. public:
void show ()
► Basically the function is resolved at run time. { cout<< "show derived class"; }
};
► It is also known as late binding.

Page 35 Maharashtra State Board of Technical Education 4 July 2020


Difference between Compile time and Runtime Polymorphism

► Compile Time ► Runtime


► In this polymorphism, an object is bound to its ► In this polymorphism, selection of appropriate
function call at compile time. function is done at run time.

► Function to be called is unknown until ► Functions to be called are known well before.
appropriate selection is made.

► This does not require use of pointers to object. ► This requires use of pointers to object
► Function calls execution are faster ► Function calls execution are slower
► Also called as early binding, Static binding ► Also called as late binding, dynamic binding.
► It is implemented with operator overloading or ► It is implemented with virtual function.
function overloading

Page 36 Maharashtra State Board of Technical Education 4 July 2020


Learning Outcome 4 : Students will
be able to develop program using
function overloading

Written by
What we will learn today

1. Function Overloading Key takeaways


Concept of function Overloading

Page 38 Maharashtra State Board of Technical Education 4 July 2020


Concept Map

class

Method(x) Method(x, y) Method(x,y , z)

Page 39 Maharashtra State Board of Technical Education 4 July 2020


Learning Objective/ Key learning

► To use Function Overloading.


► Explain how Polymorphism is achieved using function overloading?

Page 40 Maharashtra State Board of Technical Education 4 July 2020


Concept Explanation: FUNCTION OVERLOADING

► What is overloading?

❑ Overloading means assigning multiple meanings to a function name or an operator symbol.


❑ It allows multiple definitions of a function with the same name, but different signature.

► C++ Supports Polymorphism


❑ Function Overloading
❑ Operator Overloading
Compile time

Function Overloading Operator Overloading

Page 41 Maharashtra State Board of Technical Education 4 July 2020


Concept Explanation: FUNCTION OVERLOADING

► In C++ two functions can share the same name as long as their parameter declarations are different.

► In this situation, the functions that share the same name are said to be overloaded, and the process
is referred to as function overloading.
► The secret to function overloading is that each function should use either :
❑ Different types of parameters such as int, float, etc.
❑ Different number of parameters such as function1 contains 2 parameters and function2 contains
4 parameters.

42

Page 42 Maharashtra State Board of Technical Education 4 July 2020


Example :

► Function Overloading can be written as :


► Different types of parameters
In this type, we define two or more functions with same name and same number of parameters, but
the type of parameters is different.
► Different Numbers of parameters
In this type of function overloading, we define two functions with the same name but different
numbers of parameters of the same type.
► Example

Different Types of Parameters Different Numbers of Parameters

void addition(int num1, int num2); void area(float radius);


void addition(float num1, float num2); void area(float length, float breadth)

Page 43 Maharashtra State Board of Technical Education 4 July 2020


FUNCTION OVERLOADING

► In this example the function’s basic execution is to perform addition of two numbers.
► The name of both the functions is same but the datatype of the parameter of both the functions are
different.
► So while compiling if the data passed to the function is of integer type then the compiler will execute
the definition of that function.

44

Page 44 Maharashtra State Board of Technical Education 4 July 2020


FUNCTION OVERLOADING

► In this example the function’s basic execution is to calculate the area of different shapes.

► The name is same of both function, but the number of parameters are different.
► This helps compiler to help which function to call during the compilation process.

Page 45 Maharashtra State Board of Technical Education 4 July 2020


PROGRAM FOR FUNCTION OVERLOADING :

Program with two sum functions one with


two integer arguments and another with
three integer arguments

Output Of Program

Page 46 Maharashtra State Board of Technical Education 4 July 2020


Advantages of Function Overloading

► The main advantage of function overloading


► Improve the code readability and
► Allows code reusability.

Page 47 Maharashtra State Board of Technical Education 4 July 2020


Concept Map

Operator
(+)

Addition Concatenation
(2+3) (“ABC”+”DEF”=“ABCDEF”)

Page 48 Maharashtra State Board of Technical Education 4 July 2020


Learning Objective/ Key learning

► To use operator Overloading in program.


► State the operators which can not be overloaded.

Page 49 Maharashtra State Board of Technical Education 4 July 2020


Concept Explanation: OPERATOR OVERLOADING

► What is Overloading?

❑ Overloading means assigning multiple meanings to a function name or an operator symbol.


❑ It allows multiple definitions of a function with the same name, but different signatures.

► C++ supports Polymorphism

❑ Function Overloading
Compile time
❑ Operator overloading

Function Overloading Operator Overloading

50

Page 50 Maharashtra State Board of Technical Education 4 July 2020


Concept Explanation: OPERATOR OVERLOADING

► In C++ we can specify new meaning to an existing operator which is called as Operator overloading.

► In overloading, the operators are implemented as functions using the operator keyword.
► We can redefine or overload some of the built-in operators by giving user defined meaning to it.
► For example, we can overload an operator ‘+’ in a class for String so that we can concatenate two
strings by just using ‘+’.

Page 51 Maharashtra State Board of Technical Education 4 July 2020


Concept Explanation: OPERATOR OVERLOADING

► Example
The input/output operators << and >> are good examples of operator overloading

Object of ostream class

cout<<“HELLO WORLD!”;

Overloaded insertion
operator
The built-in definition of the << operator is for shifting of bits.
It is also used for displaying the values of various data types.

Page 52 Maharashtra State Board of Technical Education 4 July 2020


Concept Explanation: OPERATOR OVERLOADING

Syntax and Example :


► To define an additional task to an operator, operator function is used. The general form is .

Keyword Operator (symbol) to


be overloaded
Return type classname :: operator op (arglist)
{
Function body //task defined
}
► Where return type is the type of value returned by the specified operation and op is the operator
being overloaded. Operator op is the function name.
► Example
Time Time::operator+(Time t1)

Page 53 Maharashtra State Board of Technical Education 4 July 2020


OPERATOR OVERLOADING

► Almost all operators in C++ can be overloaded except the given below:

1. Class member operators (.)

.
2. Scope resolution operator( :: )

3. Sizeof operator(sizeof)
sizeof() Operator ::
4. Conditional oprator( ?: )

54
?:

Page 54 Maharashtra State Board of Technical Education 4 July 2020


Concept Explanation: OVERLOADING UNARY AND BINARY OPERATOR

► Two types of operators are there


► Unary Operators:
It requires only one operand to perform operation.
++ or –
Example : i++ , i--
► Binary Operators:
It requires two operands to perform operation.
+, -, *
Example : a+b, a*b

Page 55 Maharashtra State Board of Technical Education 4 July 2020


Concept Explanation: OPERATOR OVERLOADING Example

Program to Overload the '+'operator so that two void operator +()


strings can be concatenated. {
#include<iostream.h> cout<<"CON="<<strcat(a,b)<<endl;
#include<conio.h> }
#include<string.h> };
class string void main()
{ {
char a[20],b[20]; clrscr();
public: string s;
void getdata() s.getdata();
{ + s; Output

cout<<"Enter two strings::"; getch();


cin>>a>>b; }
}

Page 56 Maharashtra State Board of Technical Education 4 July 2020


Concept Explanation: OPERATOR OVERLOADING Example

Program to Overload unary '-' operator so that when it is feet--;


used with object of this class it will decrement values of inch--;
inches by 1. }
#include<iostream.h> void display()
{
class distance
cout<<" feet= "<<feet;
{ cout<<"inches= "<<inch<<endl;
float feet,inch; }
public: };
void getdata() void main()
{ {
distance d;
cout<<"Enter feet and inches ::"<<endl;
d.getdata(); Output
cin>>feet>>inch; -d;
} d.display();
void operator -() }
{
Page 57 Maharashtra State Board of Technical Education 4 July 2020
Rules of Operator Overloading:
► Only existing operators can be overloaded. New operators cannot be created.
► The overloaded operator must have at least one operand that is of user-defined type.
► We cannot change the basic meaning of an operator. That is, we cannot redefine the plus (+)
operator to subtract one value from the other.
► Overloaded operators follow the syntax rules of the original operators.
► There are some operators that cannot be overloaded.
► We cannot use friend functions to overload certain operator.
► Unary operators, overloaded by means of a member function, take no explicit arguments and return
no explicit values. But those overloaded by means of a friend return (din);
► Function take one reference argument.
► Binary operators overloaded through a member function take one explicit argument and those which
one overloaded through a friend function take two
► When using binary operators overloaded through a member function, the left-hand operand must be
an object of the relevant class.
► Binary arithmetic operators such as +, - *, and / must explicitly return a value. They must not attempt
to change their own arguments.
Page 58 Maharashtra State Board of Technical Education 4 July 2020
What we will learn today

1 Runtime Polymorphism Key takeaways

2. Virtual functions Concept of Virtual function

3. Rules of virtual functions

4. Pure virtual function

Page 59 Maharashtra State Board of Technical Education 4 July 2020


Concept Map

Superclass obj= new SubClass

SuperClass

Extends

Subclass

Page 60 Maharashtra State Board of Technical Education 4 July 2020


Learning Objective/ Key learning

► What is runtime polymorphism?

► To use virtual function in program.

► What are rules for virtual function.

Page 61 Maharashtra State Board of Technical Education 4 July 2020


Concept Explanation: RUNTIME POLYMORPHISM

► To achieve Run time polymorphism, C++ supports a mechanism known as virtual function.

Page 62 Maharashtra State Board of Technical Education 4 July 2020


Concept Explanation: RUNTIME POLYMORPHISM

► What is Runtime Polymorphism?


► The address of function to be called is determined at the runtime rather than
compile time.
► The compiler adds code that identifies the kind of object at runtime then gives
the call with the right function definition
► It is also known as late binding or dynamic binding and overriding as well.
► Late binding can be implemented by using virtual function.
► It provides slow execution as compare to early binding.
63

Page 63 Maharashtra State Board of Technical Education 4 July 2020


Concept : Virtual Function

► Virtual function belongs to runtime polymorphism in C++.


► A virtual function is a member function in the base class that you expect to redefine
in derived class.
► Virtual functions are declared with a keyword “virtual” in the base class.
► When a virtual function is declared compiler decides to execute a function based on
the type of object pointed by the base pointer and not on the type of pointer.
► Example :
virtual void draw();

Page 64 Maharashtra State Board of Technical Education 4 July 2020


Concept virtual function

► Rules of virtual function :

► The virtual function must be members of some class.

► They cannot be static members.

► They are accessed by using object pointers.

► A virtual function can be friend of another class.

► A virtual function in a base class must be defined, even though it may not be used

Page 65 Maharashtra State Board of Technical Education 4 July 2020


Example of Virtual Function :

Program Output

Program for virtual function

Page 66 Maharashtra State Board of Technical Education 4 July 2020


Concept : Pure virtual function

► A pure virtual function is a function declared in a base class that has no definition.

► The compiler requires each derived class to either define the function or redeclare it as a pure
virtual function.
► Such functions are also called as ’do-nothing’ functions.
► Ex:-
class ABC
{
public:
virtual void display( )=0; 67
};

Page 67 Maharashtra State Board of Technical Education 4 July 2020


Pure virtual Function example:

Program for Pure virtual


function

Program Output

Page 68 Maharashtra State Board of Technical Education 4 July 2020


References

► https://msbte.org.in/
► PPT: Jaishree Sudhakar Anerao (Lecturer, Department of Computer Engineering[NBA Accredited],Vivekanand
Education Society’s Polytechnic, Mumbai)

Page 69 Maharashtra State Board of Technical Education 4 July 2020

You might also like