pure virtual function or abstract class in C++

A pure virtual function is a virtual function whose declaration ends in =0. A pure virtual function implicitly makes the class it is defined for abstract class. Abstract classes cannot be instantiated. Derived classes need to override/implement all inherited pure virtual functions. If they do not, they too will become abstract. An interesting 'feature' of C++ is that a class can define a pure virtual function that has an implementation.

Syntax:-
//Abstract Class
class Base{
// ...
virtual void func() = 0; //pure virtual function
// ...
};

Example:-

C++ program for pure virtual function and abstract class.
#include<iostream.h>
#include<conio.h>
//Abstract class
class vol{
public:
//Pure virtual function
virtual void volume(){}=0;
};
class cube:public vol{
public:
void volume(){
cout<<"Volume function of derived class"<<endl;
}};
void main(){
cube c;
clrscr();
c.volume();
getch();
}

No comments:

Post a Comment