info@tutsfinder.in



Interface


Interface contains only undefined methods i.e. abstract methods(methods without body). A class can implement interface through implements keyword.

Interfaces cannot be instantiated, but can be implemented.

The methods we declare in interface, it is necessary to define them in the class in which we are implementing them otherwise compiler gives an error.

Abstraction can be achieved in C++ by using Abstract class and Interfaces.

Abstract Class – In C++, a class is made abstract class by declaring at least one of its function as pure virtual function. In pure virtual function just placing “=0” in its declaration.



Program to demonstrate abstract claa with on virtual function –

#include <iostream> 
using namespace std;  
 class Vehicle    
{    
    public:   
    virtual void run()=0;    
};    
 class Bike : Vehicle    
{    
    public:  
     void run()    
    {    
        cout << " Bike is running..." << endl;    
    }    
};    
class Car : Vehicle    
{    
    public:  
     void run()    
    {    
        cout << "Car is running..." << endl;    
    }    
};    
int main( ) {  
    Bike bike;  
    Car car;  
    bike.run();    
    car.run();   
   return 0;  
} 


Output –

Bike is running...
Car is running...


Rules of Abstract Class

1. Any class that has a pure virtual function is an abstract class.

2. We cannot create the instance of abstract class.

3. We can create pointer and reference of base abstract class points to the instance of child class

4. Abstract class can have constructors.

5. If the derived class does not implement the pure virtual function of parent class then the derived class becomes abstract.