In C++, there is a way to describe the behavior of a class without committing to a particular implementation of that class. This feature is offered by C++ objects and classes. Using abstract classes, you can implement the C++ interface.
Data abstraction and abstract classes are not the same. Data abstraction is all about keeping important details separate from associated data. You can say that interfaces and abstract classes convey the same idea.
Abstract class is nothing but a class with pure virtual function. In C++, it is a member of a function in a class that we declare in the base class and also we redefine it in a revived class.
Importance of C++ Interface
Suppose you created a class named OS with data members Windows, Linux and Mac with member functions such as size(), type() and feature().
Lets say that the size of each operating system is fixed and cannot be altered. But different operating systems have different size. In one way, you can implement the class OS for the function size() by making this function an abstract. In this way, we can make sure that the size of all operating systems is fixed. Below is the code to solve the above problem:
#include <iostream>
using namespace std;
class OS
{
public:
virtual void size() = 0;
void type()
{
cout<<"It is a windows operating system!"<<endl;
}
};
class Windows: public OS
{
public:
void size()
{
cout<<"The size is 4.90gb!"<<endl;
}
};
int main()
{
cout<<"WebTutor Tutorial: C++ Interfaces!"<<endl<<endl;
Windows data;
data.size();
data.type();
return 0;
}
Output
You should follow the rules before working with the interfaces in the C++ programming language.
- You can only declare a pure virtual function but you cannot define it.
- You can only assign O to the pure virtual function.
- You cannot create an instance of a class
- You can create a pointer to the instance of the derived class with a reference of a base abstract class.
Comments (0)