CPP Language / Virtual and pure virtual functions

Virtual Function Pure Virtual Function
It has their definition in the class. It has no definition in the class.
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
Program for Virtual function Output

#include
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;
}

In Derived

Program for Pure virtual function Output

#include
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;
b = &dobj;
b->s();// prints"D::s() called"
}

Virtual Function in Derived class


Home     Back