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

Stack of Data structure
Stack of Data structureStack of Data structure
Stack of Data structure
Sheikh Monirul Hasan
 
Class and object in c++
Class and object in c++Class and object in c++
Class and object in c++
NainaKhan28
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
Anil Bapat
 
Inheritance and Polymorphism
Inheritance and PolymorphismInheritance and Polymorphism
Inheritance and Polymorphism
BG Java EE Course
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
rajshreemuthiah
 
18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operatorSAFFI Ud Din Ahmad
 
Overview of OOP with Memes.pptx
Overview of OOP with Memes.pptxOverview of OOP with Memes.pptx
Overview of OOP with Memes.pptx
ratulyeasirarafat
 
Abstract method
Abstract methodAbstract method
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
Laxman Puri
 
Python and CSV Connectivity
Python and CSV ConnectivityPython and CSV Connectivity
Python and CSV Connectivity
Neeru Mittal
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
Maaz Hasan
 
Friend function in c++
Friend function in c++ Friend function in c++
Friend function in c++
University of Madras
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
Sameer Rathoud
 
Python Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaPython Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | Edureka
Edureka!
 
operator overloading & type conversion in cpp
operator overloading & type conversion in cppoperator overloading & type conversion in cpp
operator overloading & type conversion in cpp
gourav kottawar
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
GauravPatil318
 
Generic programming in java
Generic programming in javaGeneric programming in java
Generic programming in java
anshu_atri
 
Heap and heapsort
Heap and heapsortHeap and heapsort
Heap and heapsort
Amit Kumar Rathi
 
Circular linked list
Circular linked listCircular linked list
Circular linked listdchuynh
 

What's hot (20)

Stack of Data structure
Stack of Data structureStack of Data structure
Stack of Data structure
 
Class and object in c++
Class and object in c++Class and object in c++
Class and object in c++
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
 
Inheritance and Polymorphism
Inheritance and PolymorphismInheritance and Polymorphism
Inheritance and Polymorphism
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
 
inheritance
inheritanceinheritance
inheritance
 
18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator
 
Overview of OOP with Memes.pptx
Overview of OOP with Memes.pptxOverview of OOP with Memes.pptx
Overview of OOP with Memes.pptx
 
Abstract method
Abstract methodAbstract method
Abstract method
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 
Python and CSV Connectivity
Python and CSV ConnectivityPython and CSV Connectivity
Python and CSV Connectivity
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Friend function in c++
Friend function in c++ Friend function in c++
Friend function in c++
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
 
Python Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaPython Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | Edureka
 
operator overloading & type conversion in cpp
operator overloading & type conversion in cppoperator overloading & type conversion in cpp
operator overloading & type conversion in cpp
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
Generic programming in java
Generic programming in javaGeneric programming in java
Generic programming in java
 
Heap and heapsort
Heap and heapsortHeap and heapsort
Heap and heapsort
 
Circular linked list
Circular linked listCircular linked list
Circular linked list
 

Similar to Example for Virtual and Pure Virtual function.pdf

Polymorphism
PolymorphismPolymorphism
Polymorphism
Prof .Pragati Khade
 
object oriented programming language.pptx
object oriented programming language.pptxobject oriented programming language.pptx
object oriented programming language.pptx
syedabbas594247
 
+2 CS class and objects
+2 CS class and objects+2 CS class and objects
+2 CS class and objectskhaliledapal
 
C questions
C questionsC questions
C questions
parm112
 
Pure virtual function and abstract class
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract class
Amit Trivedi
 
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
rayanbabur
 
Virtual function and abstract class
Virtual function and abstract classVirtual function and abstract class
Virtual function and abstract class
Shweta Shah
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Pranali Chaudhari
 
Virtual Function
Virtual FunctionVirtual Function
virtual
virtualvirtual
Polymorphism Using C++
Polymorphism Using C++Polymorphism Using C++
Polymorphism Using C++
PRINCE KUMAR
 
UNIT IV (1).ppt
UNIT IV (1).pptUNIT IV (1).ppt
UNIT IV (1).ppt
VGaneshKarthikeyan
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programming
nirajmandaliya
 
virtual function
virtual functionvirtual function
virtual function
VENNILAV6
 
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
 
Virtual function
Virtual functionVirtual function
Virtual function
sdrhr
 
CST 203 Lecture 7.pptx
CST 203 Lecture 7.pptxCST 203 Lecture 7.pptx
CST 203 Lecture 7.pptx
DrKalkaDubey1
 
Classes-and-Objects-in-C++.pdf
Classes-and-Objects-in-C++.pdfClasses-and-Objects-in-C++.pdf
Classes-and-Objects-in-C++.pdf
ismartshanker1
 
Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)nirajmandaliya
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++
Rabin BK
 

Similar to 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++
 

More from 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
 
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
 

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
 
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
 

Recently uploaded

MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
Vijay Dialani, PhD
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
ChristineTorrepenida1
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Intella Parts
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
gestioneergodomus
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Soumen Santra
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
Basic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparelBasic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparel
top1002
 

Recently uploaded (20)

MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
Basic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparelBasic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparel
 

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