SlideShare a Scribd company logo
Pointers, Virtual Functions and
Polymorphism
SUBMITTED BY
S.Nandhini
Msc (CS&IT)
NSCAS
SYNOPSIS
 Introduction
 Pointers
 Pointers to objects
 This pointer
 Pointer to derived classes
 Virtual functions
 Virtual constructors and destructors
Achieving polymorphism
polymorphism
Compile time Run time
Function
overloading
Operator
overloading
Virtual
functions
Function overloading:
An overloaded function can have multiple
definitions for the same function name in the same
scope.
Function declarations cannot be
overloaded if they differ only by return type.
Operator overloading:
It is one of the many exciting features of
c++.
important technique that has enhanced
the power of extensibility of c++.
Virtual functions:
we use pointer to base class to refer to
all the derived objects.
Introduction polymorphism in
c++
 Polymorphism is one of the crucial features of oop.
 Polymorphism divide in 2 types
 Compile time
 Run time
 Compile time Polymorphism
 Uses static or early binding
 Ex. Function and operator overloading
 Run time Polymorphism
 Uses Dynamic or early binding
 EX.Virtual Functions
compile time Polymorphism
 Function overloading is an example of
compile time polymorphism
 This decision of binding among several
function is taken by considering formal
arguments of the function , their data type
and their sequence.
Run time polymorphism
 It is also known as dynamic binding, late binding
and overriding as well
 It provides slow execution as compare to early
binding because it is known at run time
 Run time polymorphism is more flexible as all
things execute at run time.
Run time Polymorphism
For Example:
Class A
{
int x;
public:
void show() {…..}
};
class B : public A
{
int y;
public:
void show() {…..}
};
Pointers
 Pointer is a derived data type that refers to
another data variable by storing the
variable’s memory address rather than data.
 Pointer variable can also refer to (or point to)
another pointer in c++.
Declaring and Initializing
pointers
 The declaration is based on the data type of the
variable it points to.
 The declaration is based on the data type of the
variable takes the following form
 Syntax:
 data-type *pointer –variable;
 Let us declare a pointer variable, which points to an
integer variable
 int * ptr;
 we can initialize a pointer
 int* ptr ,a; // declaration
 Ptr=&a; // initialization
Example of using pointers
#include <iostream.h>
#include <conio.h>
Void main()
{
int a,*ptr1,**ptr2;
Clrscr();
Ptr1=&a;
Ptr2=&ptr1;
cout <<“The address of a :”<<ptr1<<“n”;
C 0ut <<“The address of ptr1 :”<<ptr2;
Cout <<“nn”;
Cout <<“after incrementing the address values:n”;
Ptr1+=2;
cout <<“The address of a :”<<ptr1<<“n”;
Ptr2+=2;
Cout <<“The address of ptr1 :”<<ptr2<<“n”;
}
Output:
The address of a:0xfb6fff4
The address of ptr1:ox8fb6ff2
After incrementing the address values:
The address of a:ox8fb6fff8
The address of a:ox8fb6fff6
Manipulation of pointers
We can manipulate a pointer with the
indirection operator ,i.e.,’*’which is also
known as dereference operator.
Syntax:
*pointer_variable
Manipulate of pointers
#include<iostream.h>
#include<conio.h>
Int main()
{
Int a=10;
Int *ptr;
Clrscr();
Ptr=&a;
Cout<<“the value of a is:”<<*ptr;
*ptr=*ptr+a; // manipulate
Cout<<n the revised value of a is”<<a;
getch ();
return o;
}
Output:
The value of a is:10
The revised value of a
is:20
pointer Expressions and pointer arithmetic
 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
 Example:
int a[6];
int *aptr;
aptr=&a[0];
We can increment the pointer variable
aptr++ (or) ++aptr
We can decrement the pointer variable
aptr-- (or) --aptr
Using pointers with arrays and strings
 Pointer is one of the efficient tools to access
elements of an array.
 We can declare the pointers to array
 int *nptr;
 nptr=number[0];
nptr points to the first element of the integer
array, number[0].
float*fptr;
fptr=price[0];
Array of pointers
 The array of pointers represents a collection
of addresses.
 An array of pointers point to an array of data
items.
 We can declare an array of pointers as
int *inarray[10];
program array of pointer
#include<iostream.h>
Const int MAX=4;
int main()
{
Char*names[100]={“priya”,”nathiya”,”riya”,”sri”,”chitra”};
For (int i=0;i<100;i++)
{
Cout<<“value of names[“<<i<<“]=“;
Cout<<names[i]<<endI;
}
return 0;
}
Pointer and strings
 There are two ways to assign a value to a
string
 We can use the character array or variable of
type char*.
char num[]=“one”;
const char*numptr=“one”;
This pointer
This unique pointer is automatically passed to a
member function when it is called
The pointer this acts as an implicit argument to
all the member functions
This pointer is an implicit parameter to all
member functions.
Example for This pointer
Class className
{
Private:
int dataMember;
Public:
Method(int a)
{
//This pointer stores the address of object obj and access dataMemberThis -> dataMember=a;
… … ..
}
}
int main()
{
className obj;
Obj.method(5);
….. … …
}
 Pointers to objects of a base class are type
compatiable with pointers to objects of a
derived class
 A single pointer variable can be made to point
to objects belonging to different classes.
pointer to derived class
virtual functions
 A virtual function is a member function of class
that is declared within a base and re-defined in
derived class.
 Syntax:
virtual return_type function_name()
{
……..
……..
}
Rules of virtual functions
 Virtual functions are created for implementing
late binding
 The virtual functions must be members of
some class .
 They cannot be static members.
 They are accessed by using object pointers.
 A virtual function can be a friend of another
class.
Difference between virtual and pure
virtual Functions
BASIS FOR
COMPARISON
VIRTUAL FUNCTION PURE VIRTUAL FUNCTION
Base ‘virtual function’
has their definition
in the base class
‘pure virtual function’ has no
definition in the base class.
Declaration Funct_name(parame
ter_list){….};
Virtual
funct_name(parameter_list)=0;
Derived class All derived classes
may or may not
override the virtual
function of the base
class
All derived classes must
override the virtual
function of the base class.
Pure virtual functions
 A function virtual inside the base class and
redefine it in the derived classes.
 for ex. we have not defined any object of
class media and therefore the function
display().
 The base class has been defined ‘empty’.
 Virtual void display()=0;
Pure virtual function real world example
int main()
{
Shape*sptr;
Rectangle rect;
Sptr=& ret;
Sptr->set_data (5,3);
Cout<<“area of rectangle is”<<sptr->area()<<endl;
Trangle tri;
Sptr=&tri;
Sptr->set_data(4,6);
Cout<<“area of triangle is”<<sptr->area()<<endLl;
Return 0;
}
virtual constructors and destructors
 “A constructor can not be virtual “.there are some valid reasons that justify this statement
 First to create an object the constructor of the object class must be of the same type as the class.
 Class declarations that make use of destructors
class A
{
public:
~a()
{
// base class destructor
}
};
class B:publicA
{
public:
~b()
{
//derived class destructor
}
};
Main()
{
A* ptr=new B();
.
.
Delete ptr;
}
We must declare the base class destructor
Class A
{
Public:
Virtual ~A()
{
// base class destructor
}
};
Thank you

More Related Content

PPTX
This pointer
PPT
Operator Overloading
PPTX
Pointers,virtual functions and polymorphism cpp
PPTX
Constructor in java
PPTX
Object oriented programming in python
PPTX
Dynamic memory allocation in c++
PPTX
Class, object and inheritance in python
This pointer
Operator Overloading
Pointers,virtual functions and polymorphism cpp
Constructor in java
Object oriented programming in python
Dynamic memory allocation in c++
Class, object and inheritance in python

What's hot (20)

PPTX
virtual function
PPTX
classes and objects in C++
PPTX
pointer-to-object-.pptx
PDF
Constructors and destructors
PDF
Constructor and Destructor
PPTX
Constructor and destructor
PPT
Python List.ppt
PPTX
PPTX
Constructors in C++
PPTX
Virtual function in C++ Pure Virtual Function
PDF
Python Variable Types, List, Tuple, Dictionary
PPTX
Static Data Members and Member Functions
PPTX
PPTX
OOP C++
PPTX
class and objects
PPTX
Functions in python slide share
PPTX
Two dimensional arrays
PPT
Functions in c++
PPTX
Polymorphism in C++
PPTX
Command line arguments
virtual function
classes and objects in C++
pointer-to-object-.pptx
Constructors and destructors
Constructor and Destructor
Constructor and destructor
Python List.ppt
Constructors in C++
Virtual function in C++ Pure Virtual Function
Python Variable Types, List, Tuple, Dictionary
Static Data Members and Member Functions
OOP C++
class and objects
Functions in python slide share
Two dimensional arrays
Functions in c++
Polymorphism in C++
Command line arguments
Ad

Viewers also liked (20)

PPTX
07. Virtual Functions
PPT
Unit 3 principles of programming language
PPTX
pointers,virtual functions and polymorphism
PDF
08 subprograms
PPTX
Object Oriented Programming - Abstraction & Encapsulation
PPTX
9 subprograms
PPTX
PPT
Java multi threading
PPTX
1. Introduction to Association Rule 2. Frequent Item Set Mining 3. Market Bas...
PPT
Threads in Java
PPTX
Unit 3 computer system presention
PPTX
Computer networks unit iii
PDF
Networking interview questions and answers
PDF
Sliding window
PPT
Presentation on generation of languages
PPS
Protocol & Type of Networks
PPTX
Types of Networks,Network Design Issues,Design Tools
PPTX
Unit 1 introduction to computer networks
PPTX
Unit1 principle of programming language
07. Virtual Functions
Unit 3 principles of programming language
pointers,virtual functions and polymorphism
08 subprograms
Object Oriented Programming - Abstraction & Encapsulation
9 subprograms
Java multi threading
1. Introduction to Association Rule 2. Frequent Item Set Mining 3. Market Bas...
Threads in Java
Unit 3 computer system presention
Computer networks unit iii
Networking interview questions and answers
Sliding window
Presentation on generation of languages
Protocol & Type of Networks
Types of Networks,Network Design Issues,Design Tools
Unit 1 introduction to computer networks
Unit1 principle of programming language
Ad

Similar to Pointers, virtual function and polymorphism (20)

PPTX
pointer, virtual function and polymorphism
PDF
polymorphism in c++ with Full Explanation.
PPTX
Pointer and polymorphism
PPTX
Object oriented programming slides for presentation
PDF
Object Oriented Programming (OOP) using C++ - Lecture 4
PPTX
6be10b153306cc41e65403247a14a4dba5f9186aCHAPTER 2_POINTERS, VIRTUAL FUNCTIONS...
PPTX
OOPS & C++(UNIT 4)
PPT
Virtual Function and Polymorphism.ppt
PPT
Polymorphism
PPTX
Pointers in C++ object oriented programming
PPTX
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
PPTX
Introduction to pointers in c plus plus .
PPTX
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
PPTX
Pointer in C++
PDF
Polymorphism
PPTX
Presentations_PPT_ Unit-6_OOP.pptx
PDF
polymorphism for b.tech iii year students
PDF
CS225_Prelecture_Notes 2nd
PPTX
Pointers in c++
pointer, virtual function and polymorphism
polymorphism in c++ with Full Explanation.
Pointer and polymorphism
Object oriented programming slides for presentation
Object Oriented Programming (OOP) using C++ - Lecture 4
6be10b153306cc41e65403247a14a4dba5f9186aCHAPTER 2_POINTERS, VIRTUAL FUNCTIONS...
OOPS & C++(UNIT 4)
Virtual Function and Polymorphism.ppt
Polymorphism
Pointers in C++ object oriented programming
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
Introduction to pointers in c plus plus .
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Pointer in C++
Polymorphism
Presentations_PPT_ Unit-6_OOP.pptx
polymorphism for b.tech iii year students
CS225_Prelecture_Notes 2nd
Pointers in c++

More from lalithambiga kamaraj (20)

PPTX
Firewall in Network Security
PPTX
Data Compression in Multimedia
PPTX
Data CompressionMultimedia
PPTX
Digital Audio in Multimedia
PPTX
Network Security: Physical security
PPTX
Graphs in Data Structure
PPTX
Package in Java
PPTX
Exception Handling in Java
PPTX
Data structure
PPTX
Digital Image Processing
PPTX
Digital Image Processing
PPTX
Estimating Software Maintenance Costs
PPTX
PPTX
Digital Components
PPTX
Deadlocks in operating system
PPTX
Io management disk scheduling algorithm
PPTX
Recovery system
PPTX
File management
PPTX
Preprocessor
PPTX
Firewall in Network Security
Data Compression in Multimedia
Data CompressionMultimedia
Digital Audio in Multimedia
Network Security: Physical security
Graphs in Data Structure
Package in Java
Exception Handling in Java
Data structure
Digital Image Processing
Digital Image Processing
Estimating Software Maintenance Costs
Digital Components
Deadlocks in operating system
Io management disk scheduling algorithm
Recovery system
File management
Preprocessor

Recently uploaded (20)

PPTX
Cardiovascular Pharmacology for pharmacy students.pptx
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PDF
Insiders guide to clinical Medicine.pdf
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
PDF
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
PDF
The Final Stretch: How to Release a Game and Not Die in the Process.
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
Onica Farming 24rsclub profitable farm business
PPTX
Software Engineering BSC DS UNIT 1 .pptx
DOCX
UPPER GASTRO INTESTINAL DISORDER.docx
PPTX
How to Manage Loyalty Points in Odoo 18 Sales
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
Revamp in MTO Odoo 18 Inventory - Odoo Slides
PDF
Cell Biology Basics: Cell Theory, Structure, Types, and Organelles | BS Level...
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Cardiovascular Pharmacology for pharmacy students.pptx
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
Insiders guide to clinical Medicine.pdf
NOI Hackathon - Summer Edition - GreenThumber.pptx
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
The Final Stretch: How to Release a Game and Not Die in the Process.
human mycosis Human fungal infections are called human mycosis..pptx
Renaissance Architecture: A Journey from Faith to Humanism
Onica Farming 24rsclub profitable farm business
Software Engineering BSC DS UNIT 1 .pptx
UPPER GASTRO INTESTINAL DISORDER.docx
How to Manage Loyalty Points in Odoo 18 Sales
Week 4 Term 3 Study Techniques revisited.pptx
102 student loan defaulters named and shamed – Is someone you know on the list?
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Revamp in MTO Odoo 18 Inventory - Odoo Slides
Cell Biology Basics: Cell Theory, Structure, Types, and Organelles | BS Level...
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Pharmacology of Heart Failure /Pharmacotherapy of CHF

Pointers, virtual function and polymorphism

  • 1. Pointers, Virtual Functions and Polymorphism SUBMITTED BY S.Nandhini Msc (CS&IT) NSCAS
  • 2. SYNOPSIS  Introduction  Pointers  Pointers to objects  This pointer  Pointer to derived classes  Virtual functions  Virtual constructors and destructors
  • 3. Achieving polymorphism polymorphism Compile time Run time Function overloading Operator overloading Virtual functions
  • 4. Function overloading: An overloaded function can have multiple definitions for the same function name in the same scope. Function declarations cannot be overloaded if they differ only by return type. Operator overloading: It is one of the many exciting features of c++. important technique that has enhanced the power of extensibility of c++. Virtual functions: we use pointer to base class to refer to all the derived objects.
  • 5. Introduction polymorphism in c++  Polymorphism is one of the crucial features of oop.  Polymorphism divide in 2 types  Compile time  Run time  Compile time Polymorphism  Uses static or early binding  Ex. Function and operator overloading  Run time Polymorphism  Uses Dynamic or early binding  EX.Virtual Functions
  • 6. compile time Polymorphism  Function overloading is an example of compile time polymorphism  This decision of binding among several function is taken by considering formal arguments of the function , their data type and their sequence.
  • 7. Run time polymorphism  It is also known as dynamic binding, late binding and overriding as well  It provides slow execution as compare to early binding because it is known at run time  Run time polymorphism is more flexible as all things execute at run time.
  • 8. Run time Polymorphism For Example: Class A { int x; public: void show() {…..} }; class B : public A { int y; public: void show() {…..} };
  • 9. Pointers  Pointer is a derived data type that refers to another data variable by storing the variable’s memory address rather than data.  Pointer variable can also refer to (or point to) another pointer in c++.
  • 10. Declaring and Initializing pointers  The declaration is based on the data type of the variable it points to.  The declaration is based on the data type of the variable takes the following form  Syntax:  data-type *pointer –variable;  Let us declare a pointer variable, which points to an integer variable  int * ptr;  we can initialize a pointer  int* ptr ,a; // declaration  Ptr=&a; // initialization
  • 11. Example of using pointers #include <iostream.h> #include <conio.h> Void main() { int a,*ptr1,**ptr2; Clrscr(); Ptr1=&a; Ptr2=&ptr1; cout <<“The address of a :”<<ptr1<<“n”; C 0ut <<“The address of ptr1 :”<<ptr2; Cout <<“nn”; Cout <<“after incrementing the address values:n”; Ptr1+=2; cout <<“The address of a :”<<ptr1<<“n”; Ptr2+=2; Cout <<“The address of ptr1 :”<<ptr2<<“n”; } Output: The address of a:0xfb6fff4 The address of ptr1:ox8fb6ff2 After incrementing the address values: The address of a:ox8fb6fff8 The address of a:ox8fb6fff6
  • 12. Manipulation of pointers We can manipulate a pointer with the indirection operator ,i.e.,’*’which is also known as dereference operator. Syntax: *pointer_variable
  • 13. Manipulate of pointers #include<iostream.h> #include<conio.h> Int main() { Int a=10; Int *ptr; Clrscr(); Ptr=&a; Cout<<“the value of a is:”<<*ptr; *ptr=*ptr+a; // manipulate Cout<<n the revised value of a is”<<a; getch (); return o; } Output: The value of a is:10 The revised value of a is:20
  • 14. pointer Expressions and pointer arithmetic  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  Example: int a[6]; int *aptr; aptr=&a[0]; We can increment the pointer variable aptr++ (or) ++aptr We can decrement the pointer variable aptr-- (or) --aptr
  • 15. Using pointers with arrays and strings  Pointer is one of the efficient tools to access elements of an array.  We can declare the pointers to array  int *nptr;  nptr=number[0]; nptr points to the first element of the integer array, number[0]. float*fptr; fptr=price[0];
  • 16. Array of pointers  The array of pointers represents a collection of addresses.  An array of pointers point to an array of data items.  We can declare an array of pointers as int *inarray[10];
  • 17. program array of pointer #include<iostream.h> Const int MAX=4; int main() { Char*names[100]={“priya”,”nathiya”,”riya”,”sri”,”chitra”}; For (int i=0;i<100;i++) { Cout<<“value of names[“<<i<<“]=“; Cout<<names[i]<<endI; } return 0; }
  • 18. Pointer and strings  There are two ways to assign a value to a string  We can use the character array or variable of type char*. char num[]=“one”; const char*numptr=“one”;
  • 19. This pointer This unique pointer is automatically passed to a member function when it is called The pointer this acts as an implicit argument to all the member functions This pointer is an implicit parameter to all member functions.
  • 20. Example for This pointer Class className { Private: int dataMember; Public: Method(int a) { //This pointer stores the address of object obj and access dataMemberThis -> dataMember=a; … … .. } } int main() { className obj; Obj.method(5); ….. … … }
  • 21.  Pointers to objects of a base class are type compatiable with pointers to objects of a derived class  A single pointer variable can be made to point to objects belonging to different classes. pointer to derived class
  • 22. virtual functions  A virtual function is a member function of class that is declared within a base and re-defined in derived class.  Syntax: virtual return_type function_name() { …….. …….. }
  • 23. Rules of virtual functions  Virtual functions are created for implementing late binding  The virtual functions must be members of some class .  They cannot be static members.  They are accessed by using object pointers.  A virtual function can be a friend of another class.
  • 24. Difference between virtual and pure virtual Functions BASIS FOR COMPARISON VIRTUAL FUNCTION PURE VIRTUAL FUNCTION Base ‘virtual function’ has their definition in the base class ‘pure virtual function’ has no definition in the base class. Declaration Funct_name(parame ter_list){….}; Virtual funct_name(parameter_list)=0; Derived class All derived classes may or may not override the virtual function of the base class All derived classes must override the virtual function of the base class.
  • 25. Pure virtual functions  A function virtual inside the base class and redefine it in the derived classes.  for ex. we have not defined any object of class media and therefore the function display().  The base class has been defined ‘empty’.  Virtual void display()=0;
  • 26. Pure virtual function real world example int main() { Shape*sptr; Rectangle rect; Sptr=& ret; Sptr->set_data (5,3); Cout<<“area of rectangle is”<<sptr->area()<<endl; Trangle tri; Sptr=&tri; Sptr->set_data(4,6); Cout<<“area of triangle is”<<sptr->area()<<endLl; Return 0; }
  • 27. virtual constructors and destructors  “A constructor can not be virtual “.there are some valid reasons that justify this statement  First to create an object the constructor of the object class must be of the same type as the class.  Class declarations that make use of destructors class A { public: ~a() { // base class destructor } }; class B:publicA { public: ~b() { //derived class destructor } }; Main() { A* ptr=new B(); . . Delete ptr; }
  • 28. We must declare the base class destructor Class A { Public: Virtual ~A() { // base class destructor } };