SlideShare uma empresa Scribd logo
1 de 29
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

Mais conteúdo relacionado

Mais procurados

Functions in python
Functions in pythonFunctions in python
Functions in pythoncolorsof
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++Vraj Patel
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationViji B
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in javaAhsan Raja
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingBurhan Ahmed
 
Classes and objects
Classes and objectsClasses and objects
Classes and objectsNilesh Dalvi
 
virtual function
virtual functionvirtual function
virtual functionVENNILAV6
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and PackagesDamian T. Gordon
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)Ritika Sharma
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++Rabin BK
 
Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Kamlesh Makvana
 
Structure and Typedef
Structure and TypedefStructure and Typedef
Structure and TypedefAcad
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in cPrabhu Govind
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in pythonTMARAGATHAM
 

Mais procurados (20)

Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++
 
Method overriding
Method overridingMethod overriding
Method overriding
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
File in C language
File in C languageFile in C language
File in C language
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
virtual function
virtual functionvirtual function
virtual function
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Unary operator overloading
Unary operator overloadingUnary operator overloading
Unary operator overloading
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++
 
Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function
 
Structure and Typedef
Structure and TypedefStructure and Typedef
Structure and Typedef
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in c
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 

Destaque

Unit 3 principles of programming language
Unit 3 principles of programming languageUnit 3 principles of programming language
Unit 3 principles of programming languageVasavi College of Engg
 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismrattaj
 
Object Oriented Programming - Abstraction & Encapsulation
Object Oriented Programming - Abstraction & EncapsulationObject Oriented Programming - Abstraction & Encapsulation
Object Oriented Programming - Abstraction & EncapsulationDudy Ali
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
1. Introduction to Association Rule 2. Frequent Item Set Mining 3. Market Bas...
1. Introduction to Association Rule2. Frequent Item Set Mining3. Market Bas...1. Introduction to Association Rule2. Frequent Item Set Mining3. Market Bas...
1. Introduction to Association Rule 2. Frequent Item Set Mining 3. Market Bas...Surabhi Gosavi
 
Unit 3 computer system presention
Unit 3 computer system presentionUnit 3 computer system presention
Unit 3 computer system presentionMat_J
 
Computer networks unit iii
Computer networks    unit iiiComputer networks    unit iii
Computer networks unit iiiJAIGANESH SEKAR
 
Networking interview questions and answers
Networking interview questions and answersNetworking interview questions and answers
Networking interview questions and answersAmit Tiwari
 
Sliding window
 Sliding window Sliding window
Sliding windowradhaswam
 
Presentation on generation of languages
Presentation on generation of languagesPresentation on generation of languages
Presentation on generation of languagesRicha Pant
 
Types of Networks,Network Design Issues,Design Tools
Types of Networks,Network Design Issues,Design ToolsTypes of Networks,Network Design Issues,Design Tools
Types of Networks,Network Design Issues,Design ToolsSurabhi Gosavi
 
Unit 1 introduction to computer networks
Unit 1  introduction to computer networksUnit 1  introduction to computer networks
Unit 1 introduction to computer networkspavan kumar Thatikonda
 
Unit1 principle of programming language
Unit1 principle of programming languageUnit1 principle of programming language
Unit1 principle of programming languageVasavi College of Engg
 

Destaque (20)

Unit 3 principles of programming language
Unit 3 principles of programming languageUnit 3 principles of programming language
Unit 3 principles of programming language
 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphism
 
08 subprograms
08 subprograms08 subprograms
08 subprograms
 
Object Oriented Programming - Abstraction & Encapsulation
Object Oriented Programming - Abstraction & EncapsulationObject Oriented Programming - Abstraction & Encapsulation
Object Oriented Programming - Abstraction & Encapsulation
 
9 subprograms
9 subprograms9 subprograms
9 subprograms
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
1. Introduction to Association Rule 2. Frequent Item Set Mining 3. Market Bas...
1. Introduction to Association Rule2. Frequent Item Set Mining3. Market Bas...1. Introduction to Association Rule2. Frequent Item Set Mining3. Market Bas...
1. Introduction to Association Rule 2. Frequent Item Set Mining 3. Market Bas...
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Unit 3 computer system presention
Unit 3 computer system presentionUnit 3 computer system presention
Unit 3 computer system presention
 
Computer networks unit iii
Computer networks    unit iiiComputer networks    unit iii
Computer networks unit iii
 
Networking interview questions and answers
Networking interview questions and answersNetworking interview questions and answers
Networking interview questions and answers
 
Sliding window
 Sliding window Sliding window
Sliding window
 
Presentation on generation of languages
Presentation on generation of languagesPresentation on generation of languages
Presentation on generation of languages
 
Protocol & Type of Networks
Protocol & Type of NetworksProtocol & Type of Networks
Protocol & Type of Networks
 
Types of Networks,Network Design Issues,Design Tools
Types of Networks,Network Design Issues,Design ToolsTypes of Networks,Network Design Issues,Design Tools
Types of Networks,Network Design Issues,Design Tools
 
Unit 1 introduction to computer networks
Unit 1  introduction to computer networksUnit 1  introduction to computer networks
Unit 1 introduction to computer networks
 
Unit1 principle of programming language
Unit1 principle of programming languageUnit1 principle of programming language
Unit1 principle of programming language
 
Unit 5
Unit 5Unit 5
Unit 5
 
Network Topology
Network TopologyNetwork Topology
Network Topology
 

Semelhante a Pointers, Virtual Functions and Polymorphism Explained

pointer, virtual function and polymorphism
pointer, virtual function and polymorphismpointer, virtual function and polymorphism
pointer, virtual function and polymorphismramya marichamy
 
C++ Class & object pointer in c++ programming language
C++ Class & object pointer in c++ programming languageC++ Class & object pointer in c++ programming language
C++ Class & object pointer in c++ programming languageHariTharshiniBscIT1
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxShashiShash2
 
presentation_pointers_1444076066_140676 (1).ppt
presentation_pointers_1444076066_140676 (1).pptpresentation_pointers_1444076066_140676 (1).ppt
presentation_pointers_1444076066_140676 (1).pptgeorgejustymirobi1
 
Virtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptVirtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptishan743441
 
1. DSA - Introduction.pptx
1. DSA - Introduction.pptx1. DSA - Introduction.pptx
1. DSA - Introduction.pptxhara69
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloadingankush_kumar
 
Pointer and polymorphism
Pointer and polymorphismPointer and polymorphism
Pointer and polymorphismSangeethaSasi1
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2Prerna Sharma
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++LPU
 

Semelhante a Pointers, Virtual Functions and Polymorphism Explained (20)

pointer, virtual function and polymorphism
pointer, virtual function and polymorphismpointer, virtual function and polymorphism
pointer, virtual function and polymorphism
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
C++ Class & object pointer in c++ programming language
C++ Class & object pointer in c++ programming languageC++ Class & object pointer in c++ programming language
C++ Class & object pointer in c++ programming language
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptx
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptx
 
presentation_pointers_1444076066_140676 (1).ppt
presentation_pointers_1444076066_140676 (1).pptpresentation_pointers_1444076066_140676 (1).ppt
presentation_pointers_1444076066_140676 (1).ppt
 
c program.ppt
c program.pptc program.ppt
c program.ppt
 
Virtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptVirtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.ppt
 
1. DSA - Introduction.pptx
1. DSA - Introduction.pptx1. DSA - Introduction.pptx
1. DSA - Introduction.pptx
 
Advanced pointers
Advanced pointersAdvanced pointers
Advanced pointers
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
 
Object Oriented Programming with C++
Object Oriented Programming with C++Object Oriented Programming with C++
Object Oriented Programming with C++
 
Pointers
PointersPointers
Pointers
 
Pointer to function 2
Pointer to function 2Pointer to function 2
Pointer to function 2
 
pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
 
Pointer and polymorphism
Pointer and polymorphismPointer and polymorphism
Pointer and polymorphism
 
PSPC--UNIT-5.pdf
PSPC--UNIT-5.pdfPSPC--UNIT-5.pdf
PSPC--UNIT-5.pdf
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 

Mais de lalithambiga kamaraj (20)

Firewall in Network Security
Firewall in Network SecurityFirewall in Network Security
Firewall in Network Security
 
Data Compression in Multimedia
Data Compression in MultimediaData Compression in Multimedia
Data Compression in Multimedia
 
Data CompressionMultimedia
Data CompressionMultimediaData CompressionMultimedia
Data CompressionMultimedia
 
Digital Audio in Multimedia
Digital Audio in MultimediaDigital Audio in Multimedia
Digital Audio in Multimedia
 
Network Security: Physical security
Network Security: Physical security Network Security: Physical security
Network Security: Physical security
 
Graphs in Data Structure
Graphs in Data StructureGraphs in Data Structure
Graphs in Data Structure
 
Package in Java
Package in JavaPackage in Java
Package in Java
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Data structure
Data structureData structure
Data structure
 
Digital Image Processing
Digital Image ProcessingDigital Image Processing
Digital Image Processing
 
Digital Image Processing
Digital Image ProcessingDigital Image Processing
Digital Image Processing
 
Estimating Software Maintenance Costs
Estimating Software Maintenance CostsEstimating Software Maintenance Costs
Estimating Software Maintenance Costs
 
Datamining
DataminingDatamining
Datamining
 
Digital Components
Digital ComponentsDigital Components
Digital Components
 
Deadlocks in operating system
Deadlocks in operating systemDeadlocks in operating system
Deadlocks in operating system
 
Io management disk scheduling algorithm
Io management disk scheduling algorithmIo management disk scheduling algorithm
Io management disk scheduling algorithm
 
Recovery system
Recovery systemRecovery system
Recovery system
 
File management
File managementFile management
File management
 
Preprocessor
PreprocessorPreprocessor
Preprocessor
 
Inheritance
InheritanceInheritance
Inheritance
 

Último

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 

Último (20)

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 

Pointers, Virtual Functions and Polymorphism Explained

  • 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 } };