A class which contains at least one pure virtual functions is called an abstract class. Since abstract classes is incomplete, another class should derive it and provide definition for the pure virtual function in the abstract class.
Following are the features of abstract classes:
- Abstract class must contain at least one pure virtual functions.
- Objects cannot be created for abstract classes. But pointer can be created.
- Classes inheriting abstract classes must provide definitions for all pure virtual function in the abstract class. Otherwise, the sub class also becomes abstract classes.
- Abstract classes can have non-virtual functions and data member.
Following are the uses of an abstract class:
- An abstract class provides a commons standard interface for all the sub classes.
- Abstract classes allow new features to be easily added to an existing applications.
Following program demonstrate pure virtual function, late binding and an abstract classes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
#include <iostream> using namespace std; class Shapes //Abstract classes { public: virtual void areas() = 0; virtual void peris() = 0; }; class Rectangles: public Shapes //Concrete class { private: int ls; int bs; public: Rectangle(int ls, int bs) { this -> ls = ls; this -> bs = bs; } void area() { cout << “Area of rectangle: “ << (ls * bs) << endl; } void peri() { cout << “Perimeter of rectangle: “ << 2 * (ls + bs) << endl; } }; class Circle: public Shapes //Concrete classes { private: int rs; public: Circle(int rs) { this -> rs = rs; } void area() { cout << "Area of circle: " << (3.14 * rs * rs) << endl; } void peri() { cout << "Perimeter of circle: " << (2 * 3.14 * rs) << endl; } }; int main() { Shape * ss; Rectangle r(10, 20); Circle c(4); s = & rs; s -> areas(); //late binding s -> peris(); //late binding s = & cs; s -> areas(); //late binding s -> peris(); //late binding return 0; } |
Output for the above program is as follows:
1 2 3 4 5 6 |
Arearectangle: 200 Perimeterof rectangle: 60 Area circle: 50.24 Perimeterof circle: 25.12 |
Take your time to comment on this article.