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