Abstract classes and pure virtual functions

Pure Virtual function

A virtual function with no definition is pure virtual function. It is set to 0.


 class polygon  
 {  
   float area;  
 public:  
   virtual float find_area()=0;  
   void print_area();  
 }  
 void polygon::print_area()  
 {  
   cout<<area<<endln;  
 }  
Abstract class

A class which contains a pure virtual function becomes an abstract class. The definition of the class is incomplete.  An abstract class can not be instantiated. But pointers and references can be created from this class.


 int main()  
 {  
   polygon p1;//Error - object can not be created  
   polyton *p2;  
   ------  
 }  

Pure virtual functions are inherited in the derived classes. So these classes become abstract unless they define pure virtual function.


 class triangle:public polygon  
 {  
 float base,height;  
  public:  
 float find_area();  
 .......  
 };  
 float triangle::find_area()  
 {  
   return 0.5*base*height;  
 }  
 class square:public polygon  
 {  
  };  
 int main()  
 {  
    triangle obj1;//no error. Triangle is not an abstract class  
    square obj2;//error. Square has no definition for find_area. Hence abstract  
    polygon *p1 = &obj1;  
    polygon &re1 = obj1;  
 }  

In triangle class the find_area function is defined. But square class does not provide definition for that pure virtual function. Hence triangle is not abstract class, but square is.

Also observe how we can define pointers and references of abstract class and assign them to derived class objects.  

Abstract class and interface

 Unlike java, there is no keyword interface in c++. In c++ interfaces are implemented as abstract classes.

Comments

Popular Posts