SlideShare a Scribd company logo
Example for Virtual Function and
Pure Virtual Function
1
Prepared by
Dr.S.Raja Ratna
2
Virtual Function
● A virtual function is a member function which is declared within a
base class and is re-defined (overridden) by a derived class.
● They are mainly used to achieve Runtime polymorphism. The
resolving of function call is done at runtime.
● It is not mandatory for the derived class to override (or re-define the
virtual function), in that case, the base class version of the function
is used.
● Functions are declared with a virtual keyword in base class.
Rules for Virtual Functions
● Virtual functions cannot be static.
● A virtual function can be a friend function of another class.
● Virtual functions should be accessed using pointer or reference of base
class type to achieve runtime polymorphism.
● The prototype of virtual functions should be the same in the base as well
as derived class.
● They are always defined in the base class and overridden in a derived
class.
● A class may have virtual destructor but it cannot have a virtual
constructor.
3
Example 1 (Virtual Function)
#include<iostream>
using namespace std;
class base {
public:
virtual void print()
{
cout << "print base classn"; }
void show()
{
cout << "show base classn";
}
};
class derived : public base {
public:
void print()
{
cout << "print derived classn";
}
4
void show()
{
cout << "show derived classn";
}
};
int main()
{
base *bptr;
derived d;
bptr = &d;
// Virtual function, binded at runtime
bptr->print();
// Non-virtual function, binded at compile time
bptr->show();
return 0;
}
Output:
print derived class
show base class
5
Explanation for Example 1:
● Runtime polymorphism is achieved only through a pointer (or reference) of
base class type.
● Also, a base class pointer can point to the objects of base class as well as
to the objects of derived class. In above code, base class pointer ‘bptr’
contains the address of object ‘d’ of derived class.
● Late binding (Runtime) is done in accordance with the content of pointer )
and Early binding (Compile time) is done according to the type of pointer.
● Since print() function is declared with virtual keyword so it will be bound at
runtime (output is print derived class as pointer is pointing to object of
derived class) and show() is non-virtual so it will be bound during compile
time (output is show base class as pointer is of base type).
6
Example 2 (Virtual Function)
#include <iostream>
class A
{
int x=5;
public:
void display()
{
cout << "Value of x is : " << x;
}
};
class B: public A
{
int y = 10;
public:
void display()
{
cout << "Value of y is : " <<y;
}
};
7
int main()
{
A *a;
A a1;
B b;
a = & a1;
a1->display();
a = &b;
a->display();
return 0;
}
Output:
Value of x is : 5
Value of y is : 10
8
Explanation for Example 2
• In the above example, * a is the base class pointer.
• The pointer can only access the base class members but not the members
of the derived class.
• Although C++ permits the base pointer to point to any object derived from
the base class, it cannot directly access the members of the derived class.
• Therefore, there is a need for virtual function which allows the base pointer
to access the members of the derived class.
9
Pure Virtual Function
• A virtual function is not used for performing any task. It only serves as a
placeholder.
• When the function has no definition, such function is known as "do-
nothing" function.
• The "do-nothing" function is known as a pure virtual function. A pure
virtual function is a function declared in the base class that has no definition
relative to the base class.
• A class containing the pure virtual function cannot be used to declare the
objects of its own, such classes are known as abstract base classes.
10
Example (Pure Virtual Function)
#include <iostream>
class Base
{
public:
virtual void show() = 0;
};
class Derived : public Base
{
public:
void show()
{
cout << "Derived class is derived from the base class.“ ;
}
};
11
int main()
{
Base *bptr; //Base b;
Derived d;
bptr = &d;
bptr->show();
return 0;
}
Output:
Derived class is derived from the base class.
● In the above example, the base class contains the pure virtual function.
Therefore, the base class is an abstract base class. We cannot create
the object of the base class.
12

More Related Content

What's hot (20)

Functions in c
Functions in cFunctions in c
Functions in c
kalavathisugan
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
Ritika Sharma
 
Functions in C
Functions in CFunctions in C
Functions in C
Kamal Acharya
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
Dr.Neeraj Kumar Pandey
 
virtual function
virtual functionvirtual function
virtual function
VENNILAV6
 
structure and union
structure and unionstructure and union
structure and union
student
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
Haresh Jaiswal
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
Pooja Jaiswal
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
Spotle.ai
 
Functions in python
Functions in pythonFunctions in python
Functions in python
colorsof
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
Prof. Dr. K. Adisesha
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
Damian T. Gordon
 
Function overloading
Function overloadingFunction overloading
Function overloading
Prof. Dr. K. Adisesha
 
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...
Simplilearn
 
Java package
Java packageJava package
Java package
CS_GDRCST
 
Structure in c
Structure in cStructure in c
Structure in c
Prabhu Govind
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
Mohammed Sikander
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
Ritika Sharma
 
virtual function
virtual functionvirtual function
virtual function
VENNILAV6
 
structure and union
structure and unionstructure and union
structure and union
student
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
Pooja Jaiswal
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
Spotle.ai
 
Functions in python
Functions in pythonFunctions in python
Functions in python
colorsof
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
Damian T. Gordon
 
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...
C++ Inheritance Tutorial | Introduction To Inheritance In C++ Programming Wit...
Simplilearn
 
Java package
Java packageJava package
Java package
CS_GDRCST
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 

Similar to Example for Virtual and Pure Virtual function.pdf (20)

22 scheme OOPs with C++ BCS306B_module4.pdf
22 scheme  OOPs with C++ BCS306B_module4.pdf22 scheme  OOPs with C++ BCS306B_module4.pdf
22 scheme OOPs with C++ BCS306B_module4.pdf
sindhus795217
 
polymorphism for b.tech iii year students
polymorphism for b.tech iii year studentspolymorphism for b.tech iii year students
polymorphism for b.tech iii year students
Somesh Kumar
 
6. Virtual base class.pptx and virtual function
6. Virtual base class.pptx and virtual function6. Virtual base class.pptx and virtual function
6. Virtual base class.pptx and virtual function
archana22486y
 
Virtual Function
Virtual FunctionVirtual Function
Virtual Function
Lovely Professional University
 
Virtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptVirtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.ppt
ishan743441
 
Virtual function
Virtual functionVirtual function
Virtual function
zindadili
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
Prof .Pragati Khade
 
OOPS & C++(UNIT 4)
OOPS & C++(UNIT 4)OOPS & C++(UNIT 4)
OOPS & C++(UNIT 4)
Dr. SURBHI SAROHA
 
B.sc CSIT 2nd semester C++ Unit6
B.sc CSIT  2nd semester C++ Unit6B.sc CSIT  2nd semester C++ Unit6
B.sc CSIT 2nd semester C++ Unit6
Tekendra Nath Yogi
 
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
 
polymorpisum-140106223024-phpapp01.pdf
polymorpisum-140106223024-phpapp01.pdfpolymorpisum-140106223024-phpapp01.pdf
polymorpisum-140106223024-phpapp01.pdf
BapanKar2
 
Lecture 7, c++(complete reference,herbet sheidt)chapter-17.
Lecture 7, c++(complete reference,herbet sheidt)chapter-17.Lecture 7, c++(complete reference,herbet sheidt)chapter-17.
Lecture 7, c++(complete reference,herbet sheidt)chapter-17.
Abu Saleh
 
polymorphism.pdf
polymorphism.pdfpolymorphism.pdf
polymorphism.pdf
riyawagh2
 
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptxObject Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
RashidFaridChishti
 
Virtual function and abstract class
Virtual function and abstract classVirtual function and abstract class
Virtual function and abstract class
Shweta Shah
 
Dynamic Polymorphism in C++
Dynamic Polymorphism in C++Dynamic Polymorphism in C++
Dynamic Polymorphism in C++
Dharmisha Sharma
 
Object Oriented Programming (OOP) using C++ - Lecture 4
Object Oriented Programming (OOP) using C++ - Lecture 4Object Oriented Programming (OOP) using C++ - Lecture 4
Object Oriented Programming (OOP) using C++ - Lecture 4
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
polymorphism ppt
polymorphism pptpolymorphism ppt
polymorphism ppt
sheetal singh
 
Polymorphism in C++ for beginners reference
Polymorphism  in C++ for beginners referencePolymorphism  in C++ for beginners reference
Polymorphism in C++ for beginners reference
21pd23
 
polymorphism and virtual function
polymorphism and virtual functionpolymorphism and virtual function
polymorphism and virtual function
Bhanuprataparya
 
22 scheme OOPs with C++ BCS306B_module4.pdf
22 scheme  OOPs with C++ BCS306B_module4.pdf22 scheme  OOPs with C++ BCS306B_module4.pdf
22 scheme OOPs with C++ BCS306B_module4.pdf
sindhus795217
 
polymorphism for b.tech iii year students
polymorphism for b.tech iii year studentspolymorphism for b.tech iii year students
polymorphism for b.tech iii year students
Somesh Kumar
 
6. Virtual base class.pptx and virtual function
6. Virtual base class.pptx and virtual function6. Virtual base class.pptx and virtual function
6. Virtual base class.pptx and virtual function
archana22486y
 
Virtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptVirtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.ppt
ishan743441
 
Virtual function
Virtual functionVirtual function
Virtual function
zindadili
 
B.sc CSIT 2nd semester C++ Unit6
B.sc CSIT  2nd semester C++ Unit6B.sc CSIT  2nd semester C++ Unit6
B.sc CSIT 2nd semester C++ Unit6
Tekendra Nath Yogi
 
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
 
polymorpisum-140106223024-phpapp01.pdf
polymorpisum-140106223024-phpapp01.pdfpolymorpisum-140106223024-phpapp01.pdf
polymorpisum-140106223024-phpapp01.pdf
BapanKar2
 
Lecture 7, c++(complete reference,herbet sheidt)chapter-17.
Lecture 7, c++(complete reference,herbet sheidt)chapter-17.Lecture 7, c++(complete reference,herbet sheidt)chapter-17.
Lecture 7, c++(complete reference,herbet sheidt)chapter-17.
Abu Saleh
 
polymorphism.pdf
polymorphism.pdfpolymorphism.pdf
polymorphism.pdf
riyawagh2
 
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptxObject Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
RashidFaridChishti
 
Virtual function and abstract class
Virtual function and abstract classVirtual function and abstract class
Virtual function and abstract class
Shweta Shah
 
Dynamic Polymorphism in C++
Dynamic Polymorphism in C++Dynamic Polymorphism in C++
Dynamic Polymorphism in C++
Dharmisha Sharma
 
Polymorphism in C++ for beginners reference
Polymorphism  in C++ for beginners referencePolymorphism  in C++ for beginners reference
Polymorphism in C++ for beginners reference
21pd23
 
polymorphism and virtual function
polymorphism and virtual functionpolymorphism and virtual function
polymorphism and virtual function
Bhanuprataparya
 

More from rajaratna4 (8)

Memory and Cache Coherence in Multiprocessor System.pdf
Memory and Cache Coherence in Multiprocessor System.pdfMemory and Cache Coherence in Multiprocessor System.pdf
Memory and Cache Coherence in Multiprocessor System.pdf
rajaratna4
 
Multicore processor.pdf
Multicore processor.pdfMulticore processor.pdf
Multicore processor.pdf
rajaratna4
 
Hardware Multithreading.pdf
Hardware Multithreading.pdfHardware Multithreading.pdf
Hardware Multithreading.pdf
rajaratna4
 
Flynn's classification.pdf
Flynn's classification.pdfFlynn's classification.pdf
Flynn's classification.pdf
rajaratna4
 
Classes and Errors.pdf
Classes and Errors.pdfClasses and Errors.pdf
Classes and Errors.pdf
rajaratna4
 
STLStack.pdf
STLStack.pdfSTLStack.pdf
STLStack.pdf
rajaratna4
 
Example for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdfExample for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdf
rajaratna4
 
Abstract Class and Interface.pdf
Abstract Class and Interface.pdfAbstract Class and Interface.pdf
Abstract Class and Interface.pdf
rajaratna4
 
Memory and Cache Coherence in Multiprocessor System.pdf
Memory and Cache Coherence in Multiprocessor System.pdfMemory and Cache Coherence in Multiprocessor System.pdf
Memory and Cache Coherence in Multiprocessor System.pdf
rajaratna4
 
Multicore processor.pdf
Multicore processor.pdfMulticore processor.pdf
Multicore processor.pdf
rajaratna4
 
Hardware Multithreading.pdf
Hardware Multithreading.pdfHardware Multithreading.pdf
Hardware Multithreading.pdf
rajaratna4
 
Flynn's classification.pdf
Flynn's classification.pdfFlynn's classification.pdf
Flynn's classification.pdf
rajaratna4
 
Classes and Errors.pdf
Classes and Errors.pdfClasses and Errors.pdf
Classes and Errors.pdf
rajaratna4
 
Example for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdfExample for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdf
rajaratna4
 
Abstract Class and Interface.pdf
Abstract Class and Interface.pdfAbstract Class and Interface.pdf
Abstract Class and Interface.pdf
rajaratna4
 

Recently uploaded (20)

Scilab Chemical Engineering application.pptx
Scilab Chemical Engineering  application.pptxScilab Chemical Engineering  application.pptx
Scilab Chemical Engineering application.pptx
OmPandey85
 
BEC602- Module 3-2-Notes.pdf.Vlsi design and testing notes
BEC602- Module 3-2-Notes.pdf.Vlsi design and testing notesBEC602- Module 3-2-Notes.pdf.Vlsi design and testing notes
BEC602- Module 3-2-Notes.pdf.Vlsi design and testing notes
VarshithaP6
 
MS Project - Pelaksanaan Proyek Fisik 2020
MS Project - Pelaksanaan Proyek Fisik 2020MS Project - Pelaksanaan Proyek Fisik 2020
MS Project - Pelaksanaan Proyek Fisik 2020
Bagus ardian
 
DE-UNIT-V MEMORY DEVICES AND DIGITAL INTEGRATED CIRCUITS
DE-UNIT-V MEMORY DEVICES AND DIGITAL INTEGRATED CIRCUITSDE-UNIT-V MEMORY DEVICES AND DIGITAL INTEGRATED CIRCUITS
DE-UNIT-V MEMORY DEVICES AND DIGITAL INTEGRATED CIRCUITS
Sridhar191373
 
1.9 Class,Object,Class Scope,Accessing Class members and Controlling access t...
1.9 Class,Object,Class Scope,Accessing Class members and Controlling access t...1.9 Class,Object,Class Scope,Accessing Class members and Controlling access t...
1.9 Class,Object,Class Scope,Accessing Class members and Controlling access t...
VikasNirgude2
 
1.2 Need of Object-Oriented Programming.pdf
1.2 Need of Object-Oriented Programming.pdf1.2 Need of Object-Oriented Programming.pdf
1.2 Need of Object-Oriented Programming.pdf
VikasNirgude2
 
FTS under Indiandadsadsadsadsadsadsa DTAA.pdf
FTS under Indiandadsadsadsadsadsadsa DTAA.pdfFTS under Indiandadsadsadsadsadsadsa DTAA.pdf
FTS under Indiandadsadsadsadsadsadsa DTAA.pdf
HimanshuSharma779547
 
Silent-Aire Quality Orientation - OFCI_GC - EVAP Unit REV2.pdf
Silent-Aire Quality Orientation - OFCI_GC - EVAP Unit REV2.pdfSilent-Aire Quality Orientation - OFCI_GC - EVAP Unit REV2.pdf
Silent-Aire Quality Orientation - OFCI_GC - EVAP Unit REV2.pdf
EfrainGarrilloRuiz1
 
International Journal of Advance Robotics & Expert Systems (JARES)
International Journal of Advance Robotics & Expert Systems (JARES)International Journal of Advance Robotics & Expert Systems (JARES)
International Journal of Advance Robotics & Expert Systems (JARES)
jaresjournal868
 
Java Programming Language: until 2025 and beyond
Java Programming Language: until 2025 and beyondJava Programming Language: until 2025 and beyond
Java Programming Language: until 2025 and beyond
arzu TR
 
Filters for Electromagnetic Compatibility Applications
Filters for Electromagnetic Compatibility ApplicationsFilters for Electromagnetic Compatibility Applications
Filters for Electromagnetic Compatibility Applications
Mathias Magdowski
 
Unit 6 Message Digest Message Digest Message Digest
Unit 6  Message Digest  Message Digest  Message DigestUnit 6  Message Digest  Message Digest  Message Digest
Unit 6 Message Digest Message Digest Message Digest
ChatanBawankar
 
Ceramic Multichannel Membrane Structure with Tunable Properties by Sol-Gel Me...
Ceramic Multichannel Membrane Structure with Tunable Properties by Sol-Gel Me...Ceramic Multichannel Membrane Structure with Tunable Properties by Sol-Gel Me...
Ceramic Multichannel Membrane Structure with Tunable Properties by Sol-Gel Me...
DanyalNaseer3
 
Particle Swarm Optimization by Aleksandar Lazinica (Editor) (z-lib.org).pdf
Particle Swarm Optimization by Aleksandar Lazinica (Editor) (z-lib.org).pdfParticle Swarm Optimization by Aleksandar Lazinica (Editor) (z-lib.org).pdf
Particle Swarm Optimization by Aleksandar Lazinica (Editor) (z-lib.org).pdf
DUSABEMARIYA
 
A New Enhanced Hybrid Grey Wolf Optimizer (GWO) Combined with Elephant Herdin...
A New Enhanced Hybrid Grey Wolf Optimizer (GWO) Combined with Elephant Herdin...A New Enhanced Hybrid Grey Wolf Optimizer (GWO) Combined with Elephant Herdin...
A New Enhanced Hybrid Grey Wolf Optimizer (GWO) Combined with Elephant Herdin...
Journal of Soft Computing in Civil Engineering
 
1.10 Functions in C++,call by value .pdf
1.10 Functions in C++,call by value .pdf1.10 Functions in C++,call by value .pdf
1.10 Functions in C++,call by value .pdf
VikasNirgude2
 
Full_Cybersecurity_Project_Report_30_Pages.pdf
Full_Cybersecurity_Project_Report_30_Pages.pdfFull_Cybersecurity_Project_Report_30_Pages.pdf
Full_Cybersecurity_Project_Report_30_Pages.pdf
Arun446808
 
Video Games and Artificial-Realities.pptx
Video Games and Artificial-Realities.pptxVideo Games and Artificial-Realities.pptx
Video Games and Artificial-Realities.pptx
HadiBadri1
 
Concept Learning - Find S Algorithm,Candidate Elimination Algorithm
Concept Learning - Find S Algorithm,Candidate Elimination AlgorithmConcept Learning - Find S Algorithm,Candidate Elimination Algorithm
Concept Learning - Find S Algorithm,Candidate Elimination Algorithm
Global Academy of Technology
 
Air Filter Flat Sheet Media-Catalouge-Final.pdf
Air Filter Flat Sheet Media-Catalouge-Final.pdfAir Filter Flat Sheet Media-Catalouge-Final.pdf
Air Filter Flat Sheet Media-Catalouge-Final.pdf
FILTRATION ENGINEERING & CUNSULTANT
 
Scilab Chemical Engineering application.pptx
Scilab Chemical Engineering  application.pptxScilab Chemical Engineering  application.pptx
Scilab Chemical Engineering application.pptx
OmPandey85
 
BEC602- Module 3-2-Notes.pdf.Vlsi design and testing notes
BEC602- Module 3-2-Notes.pdf.Vlsi design and testing notesBEC602- Module 3-2-Notes.pdf.Vlsi design and testing notes
BEC602- Module 3-2-Notes.pdf.Vlsi design and testing notes
VarshithaP6
 
MS Project - Pelaksanaan Proyek Fisik 2020
MS Project - Pelaksanaan Proyek Fisik 2020MS Project - Pelaksanaan Proyek Fisik 2020
MS Project - Pelaksanaan Proyek Fisik 2020
Bagus ardian
 
DE-UNIT-V MEMORY DEVICES AND DIGITAL INTEGRATED CIRCUITS
DE-UNIT-V MEMORY DEVICES AND DIGITAL INTEGRATED CIRCUITSDE-UNIT-V MEMORY DEVICES AND DIGITAL INTEGRATED CIRCUITS
DE-UNIT-V MEMORY DEVICES AND DIGITAL INTEGRATED CIRCUITS
Sridhar191373
 
1.9 Class,Object,Class Scope,Accessing Class members and Controlling access t...
1.9 Class,Object,Class Scope,Accessing Class members and Controlling access t...1.9 Class,Object,Class Scope,Accessing Class members and Controlling access t...
1.9 Class,Object,Class Scope,Accessing Class members and Controlling access t...
VikasNirgude2
 
1.2 Need of Object-Oriented Programming.pdf
1.2 Need of Object-Oriented Programming.pdf1.2 Need of Object-Oriented Programming.pdf
1.2 Need of Object-Oriented Programming.pdf
VikasNirgude2
 
FTS under Indiandadsadsadsadsadsadsa DTAA.pdf
FTS under Indiandadsadsadsadsadsadsa DTAA.pdfFTS under Indiandadsadsadsadsadsadsa DTAA.pdf
FTS under Indiandadsadsadsadsadsadsa DTAA.pdf
HimanshuSharma779547
 
Silent-Aire Quality Orientation - OFCI_GC - EVAP Unit REV2.pdf
Silent-Aire Quality Orientation - OFCI_GC - EVAP Unit REV2.pdfSilent-Aire Quality Orientation - OFCI_GC - EVAP Unit REV2.pdf
Silent-Aire Quality Orientation - OFCI_GC - EVAP Unit REV2.pdf
EfrainGarrilloRuiz1
 
International Journal of Advance Robotics & Expert Systems (JARES)
International Journal of Advance Robotics & Expert Systems (JARES)International Journal of Advance Robotics & Expert Systems (JARES)
International Journal of Advance Robotics & Expert Systems (JARES)
jaresjournal868
 
Java Programming Language: until 2025 and beyond
Java Programming Language: until 2025 and beyondJava Programming Language: until 2025 and beyond
Java Programming Language: until 2025 and beyond
arzu TR
 
Filters for Electromagnetic Compatibility Applications
Filters for Electromagnetic Compatibility ApplicationsFilters for Electromagnetic Compatibility Applications
Filters for Electromagnetic Compatibility Applications
Mathias Magdowski
 
Unit 6 Message Digest Message Digest Message Digest
Unit 6  Message Digest  Message Digest  Message DigestUnit 6  Message Digest  Message Digest  Message Digest
Unit 6 Message Digest Message Digest Message Digest
ChatanBawankar
 
Ceramic Multichannel Membrane Structure with Tunable Properties by Sol-Gel Me...
Ceramic Multichannel Membrane Structure with Tunable Properties by Sol-Gel Me...Ceramic Multichannel Membrane Structure with Tunable Properties by Sol-Gel Me...
Ceramic Multichannel Membrane Structure with Tunable Properties by Sol-Gel Me...
DanyalNaseer3
 
Particle Swarm Optimization by Aleksandar Lazinica (Editor) (z-lib.org).pdf
Particle Swarm Optimization by Aleksandar Lazinica (Editor) (z-lib.org).pdfParticle Swarm Optimization by Aleksandar Lazinica (Editor) (z-lib.org).pdf
Particle Swarm Optimization by Aleksandar Lazinica (Editor) (z-lib.org).pdf
DUSABEMARIYA
 
1.10 Functions in C++,call by value .pdf
1.10 Functions in C++,call by value .pdf1.10 Functions in C++,call by value .pdf
1.10 Functions in C++,call by value .pdf
VikasNirgude2
 
Full_Cybersecurity_Project_Report_30_Pages.pdf
Full_Cybersecurity_Project_Report_30_Pages.pdfFull_Cybersecurity_Project_Report_30_Pages.pdf
Full_Cybersecurity_Project_Report_30_Pages.pdf
Arun446808
 
Video Games and Artificial-Realities.pptx
Video Games and Artificial-Realities.pptxVideo Games and Artificial-Realities.pptx
Video Games and Artificial-Realities.pptx
HadiBadri1
 
Concept Learning - Find S Algorithm,Candidate Elimination Algorithm
Concept Learning - Find S Algorithm,Candidate Elimination AlgorithmConcept Learning - Find S Algorithm,Candidate Elimination Algorithm
Concept Learning - Find S Algorithm,Candidate Elimination Algorithm
Global Academy of Technology
 

Example for Virtual and Pure Virtual function.pdf

  • 1. Example for Virtual Function and Pure Virtual Function 1 Prepared by Dr.S.Raja Ratna
  • 2. 2 Virtual Function ● A virtual function is a member function which is declared within a base class and is re-defined (overridden) by a derived class. ● They are mainly used to achieve Runtime polymorphism. The resolving of function call is done at runtime. ● It is not mandatory for the derived class to override (or re-define the virtual function), in that case, the base class version of the function is used. ● Functions are declared with a virtual keyword in base class.
  • 3. Rules for Virtual Functions ● Virtual functions cannot be static. ● A virtual function can be a friend function of another class. ● Virtual functions should be accessed using pointer or reference of base class type to achieve runtime polymorphism. ● The prototype of virtual functions should be the same in the base as well as derived class. ● They are always defined in the base class and overridden in a derived class. ● A class may have virtual destructor but it cannot have a virtual constructor. 3
  • 4. Example 1 (Virtual Function) #include<iostream> using namespace std; class base { public: virtual void print() { cout << "print base classn"; } void show() { cout << "show base classn"; } }; class derived : public base { public: void print() { cout << "print derived classn"; } 4
  • 5. void show() { cout << "show derived classn"; } }; int main() { base *bptr; derived d; bptr = &d; // Virtual function, binded at runtime bptr->print(); // Non-virtual function, binded at compile time bptr->show(); return 0; } Output: print derived class show base class 5
  • 6. Explanation for Example 1: ● Runtime polymorphism is achieved only through a pointer (or reference) of base class type. ● Also, a base class pointer can point to the objects of base class as well as to the objects of derived class. In above code, base class pointer ‘bptr’ contains the address of object ‘d’ of derived class. ● Late binding (Runtime) is done in accordance with the content of pointer ) and Early binding (Compile time) is done according to the type of pointer. ● Since print() function is declared with virtual keyword so it will be bound at runtime (output is print derived class as pointer is pointing to object of derived class) and show() is non-virtual so it will be bound during compile time (output is show base class as pointer is of base type). 6
  • 7. Example 2 (Virtual Function) #include <iostream> class A { int x=5; public: void display() { cout << "Value of x is : " << x; } }; class B: public A { int y = 10; public: void display() { cout << "Value of y is : " <<y; } }; 7
  • 8. int main() { A *a; A a1; B b; a = & a1; a1->display(); a = &b; a->display(); return 0; } Output: Value of x is : 5 Value of y is : 10 8
  • 9. Explanation for Example 2 • In the above example, * a is the base class pointer. • The pointer can only access the base class members but not the members of the derived class. • Although C++ permits the base pointer to point to any object derived from the base class, it cannot directly access the members of the derived class. • Therefore, there is a need for virtual function which allows the base pointer to access the members of the derived class. 9
  • 10. Pure Virtual Function • A virtual function is not used for performing any task. It only serves as a placeholder. • When the function has no definition, such function is known as "do- nothing" function. • The "do-nothing" function is known as a pure virtual function. A pure virtual function is a function declared in the base class that has no definition relative to the base class. • A class containing the pure virtual function cannot be used to declare the objects of its own, such classes are known as abstract base classes. 10
  • 11. Example (Pure Virtual Function) #include <iostream> class Base { public: virtual void show() = 0; }; class Derived : public Base { public: void show() { cout << "Derived class is derived from the base class.“ ; } }; 11
  • 12. int main() { Base *bptr; //Base b; Derived d; bptr = &d; bptr->show(); return 0; } Output: Derived class is derived from the base class. ● In the above example, the base class contains the pure virtual function. Therefore, the base class is an abstract base class. We cannot create the object of the base class. 12