Search Your Topic

config
Saturday, 17 June 2017 07:30

Interfaces in C++ (Abstract Classes)

Written by
Rate this item
(0 votes)

Abstract classes are the way to achieve abstraction in C++. Abstraction in C++ is the process to hide the internal details and showing functionality only. Abstraction can be achieved by two ways:

  1. Abstract class
  2. Interface

Abstract class and interface both can have abstract methods which are necessary for abstraction.


C++ Abstract class

In C++ class is made abstract by declaring at least one of its functions as <>strong>pure virtual function. A pure virtual function is specified by placing "= 0" in its declaration. Its implementation must be provided by derived classes.

Let's see an example of abstract class in C++ which has one abstract method draw(). Its implementation is provided by derived classes: Rectangle and Circle. Both classes have different implementation.

 
  1. #include <iostream>  
  2. using namespace std;  
  3.  class Shape    
  4. {    
  5.     public:   
  6.     virtual void draw()=0;    
  7. };    
  8.  class Rectangle : Shape    
  9. {    
  10.     public:  
  11.      void draw()    
  12.     {    
  13.         cout < <"drawing rectangle..." < <endl;    
  14.     }    
  15. };    
  16. class Circle : Shape    
  17. {    
  18.     public:  
  19.      void draw()    
  20.     {    
  21.         cout <<"drawing circle..." < <endl;    
  22.     }    
  23. };    
  24. int main( ) {  
  25.     Rectangle rec;  
  26.     Circle cir;  
  27.     rec.draw();    
  28.     cir.draw();   
  29.    return 0;  
  30. }  

Output:

drawing rectangle...
drawing circle...
Read 209 times
Anish Sir

"I am delighted once again to pen the welcome note to the Tosh!Yas Technologies ."

 Call +91 74 88 34 7779  | Email : anishsingh@live.com

toshiyas.in

Leave a comment

Make sure you enter all the required information, indicated by an asterisk (*). HTML code is not allowed.