SlideShare une entreprise Scribd logo
1  sur  12
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

C++ Pointers And References
C++ Pointers And ReferencesC++ Pointers And References
C++ Pointers And References
verisan
 

Tendances (20)

Circular Queue data structure
Circular Queue data structureCircular Queue data structure
Circular Queue data structure
 
Circular queue
Circular queueCircular queue
Circular queue
 
Awt controls ppt
Awt controls pptAwt controls ppt
Awt controls ppt
 
Binary search tree
Binary search treeBinary search tree
Binary search tree
 
stack presentation
stack presentationstack presentation
stack presentation
 
Binary Search Tree and AVL
Binary Search Tree and AVLBinary Search Tree and AVL
Binary Search Tree and AVL
 
Data Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search TreeData Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search Tree
 
deque and it applications
deque and it applicationsdeque and it applications
deque and it applications
 
Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures
 
Chap 7 binary threaded tree
Chap 7 binary threaded treeChap 7 binary threaded tree
Chap 7 binary threaded tree
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
Binary search tree operations
Binary search tree operationsBinary search tree operations
Binary search tree operations
 
This pointer
This pointerThis pointer
This pointer
 
Expression trees
Expression treesExpression trees
Expression trees
 
Introduction to data structure ppt
Introduction to data structure pptIntroduction to data structure ppt
Introduction to data structure ppt
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
C++ Pointers And References
C++ Pointers And ReferencesC++ Pointers And References
C++ Pointers And References
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Stacks
StacksStacks
Stacks
 
Linked list
Linked listLinked list
Linked list
 

Similaire à Example for Virtual and Pure Virtual function.pdf

+2 CS class and objects
+2 CS class and objects+2 CS class and objects
+2 CS class and objects
khaliledapal
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
rashmita_mishra
 
Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)
nirajmandaliya
 

Similaire à Example for Virtual and Pure Virtual function.pdf (20)

Polymorphism
PolymorphismPolymorphism
Polymorphism
 
object oriented programming language.pptx
object oriented programming language.pptxobject oriented programming language.pptx
object oriented programming language.pptx
 
+2 CS class and objects
+2 CS class and objects+2 CS class and objects
+2 CS class and objects
 
C questions
C questionsC questions
C questions
 
Pure virtual function and abstract class
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract class
 
Lecture-11 Friend Functions and inline functions.pptx
Lecture-11 Friend Functions and inline functions.pptxLecture-11 Friend Functions and inline functions.pptx
Lecture-11 Friend Functions and inline functions.pptx
 
Virtual function and abstract class
Virtual function and abstract classVirtual function and abstract class
Virtual function and abstract class
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Virtual Function
Virtual FunctionVirtual Function
Virtual Function
 
virtual
virtualvirtual
virtual
 
Polymorphism Using C++
Polymorphism Using C++Polymorphism Using C++
Polymorphism Using C++
 
UNIT IV (1).ppt
UNIT IV (1).pptUNIT IV (1).ppt
UNIT IV (1).ppt
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programming
 
virtual function
virtual functionvirtual function
virtual function
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
 
Virtual function
Virtual functionVirtual function
Virtual function
 
CST 203 Lecture 7.pptx
CST 203 Lecture 7.pptxCST 203 Lecture 7.pptx
CST 203 Lecture 7.pptx
 
Classes-and-Objects-in-C++.pdf
Classes-and-Objects-in-C++.pdfClasses-and-Objects-in-C++.pdf
Classes-and-Objects-in-C++.pdf
 
Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++
 

Plus de 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
 
Multicore processor.pdf
Multicore processor.pdfMulticore processor.pdf
Multicore processor.pdf
 
Hardware Multithreading.pdf
Hardware Multithreading.pdfHardware Multithreading.pdf
Hardware Multithreading.pdf
 
Flynn's classification.pdf
Flynn's classification.pdfFlynn's classification.pdf
Flynn's classification.pdf
 
Classes and Errors.pdf
Classes and Errors.pdfClasses and Errors.pdf
Classes and Errors.pdf
 
STLStack.pdf
STLStack.pdfSTLStack.pdf
STLStack.pdf
 
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
 
Abstract Class and Interface.pdf
Abstract Class and Interface.pdfAbstract Class and Interface.pdf
Abstract Class and Interface.pdf
 

Dernier

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
dollysharma2066
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Dernier (20)

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Vivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design SpainVivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design Spain
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 

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