PREV NEXT
C++ Interfaces:
What are C++ interfaces?
- An interface is a group of related functionalities that can belong to any class. The interfaces are created using abstract class.
- Abstract classes are used to achieve the abstraction in C++ and abstraction in C++ is a process to hide the internal details and show functionality only.
- The class can be made abstract by declaring at least one of its functions as pure virtual function. A pure virtual function is implemented with a virtual keyword and has =0 in its declaration and this function is called as abstract function as it has no body.
Let us have a look at the syntax:
virtual void function() = 0;
Let us have a look at the example to understand the abstract class:
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 52 53 54 55 56 57 58 59 |
#include <iostream> using namespace std; class Fruits { public: virtual void color()=0; }; class Apple : Fruits { public: void color() { cout << "I am a red apple" <<endl; } }; class Mango : Fruits { public: void color() { cout <<"I am a yellow mango" <<endl; } }; int main( ) { Apple a; Mango m; a.color(); m.color(); return 0; } |
Rules for abstract class
- We can create a pointer and reference of base abstract class which points to the instance of child class.
- It can have constructors.
- Any class which has pure virtual function than that class is declared as abstract class.
- We cannot create an object of abstract class.