- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference between a virtual function and a pure virtual function in C++
Following table shows the difference between Virtual and Pure Virtual Function:
Virtual Function | Pure Virtual Function |
---|---|
Virtual function has their definition in the class. | Pure virtual function has no definition. |
Declaration: virtual funct_name(parameter_list) {. . . . .}; | Declaration: virtual funct_name(parameter_list)=0; |
It has no concept of derived class. | If a class contains at least one pure virtual function, then it is declared abstract. |
If required, the base class can override a virtual function. | In case of pure virtual function derived class has to definitely override the pure virtual function. |
virtual function
Example Code
#include <iostream> using namespace std; class B { public: virtual void s() //virtual function { cout<<" In Base \n"; } }; class D: public B { public: void s() { cout<<"In Derived \n"; } }; int main(void) { D d; // An object of class D B *b= &d;// A pointer of type B* pointing to d b->s();// prints"D::s() called" return 0; }
Output
In Derived
pure virtual function
Example Code
#include<iostream> using namespace std; class B { public: virtual void s() = 0; // Pure Virtual Function }; class D:public B { public: void s() { cout << " Virtual Function in Derived class\n"; } }; int main() { B *b; D dobj; // An object of class D b = &dobj;// A pointer of type B* pointing to dobj b->s();// prints"D::s() called" }
Output
Virtual Function in Derived class
Advertisements