C++ Interface (Abstract Class)
An interface describes the behavior and functionality of a class, without requiring the specific implementation of the class.
C++ interfaces are implemented usingAbstract classabstract classes. Abstract classes and data abstraction are not to be confused; data abstraction is a concept that separates implementation details from related data.
If at least one function in a class is declared as a pure virtual function, then the class is an abstract class. A pure virtual function is specified by using "= 0" in its declaration, as shown below:
DesignAbstract classThe purpose of an abstract class (often called ABC) is to provide an appropriate base class from which other classes can inherit. Abstract classes cannot be used to instantiate objects; they can only be used asinterfaceinterfaces. Attempting to instantiate an object of an abstract class will cause a compilation error.
Therefore, if a subclass of an ABC needs to be instantiated, it must implement each pure virtual function. This also means that C++ supports using ABCs to declare interfaces. If you attempt to instantiate an object of such a class without overriding the pure virtual functions in the derived class, a compilation error will occur.
A class that can be used to instantiate objects is calledConcrete class。
An instance of an abstract class
See the example below. The base class Shape provides an interfacegetArea(), implemented respectively in the two derived classes Rectangle and TrianglegetArea():
Example
When the above code is compiled and executed, it produces the following results:
Total Rectangle area: 35 Total Triangle area: 17
From the above example, we can see how an abstract class defines an interface getArea(), and how two derived classes implement this same function through different area calculation algorithms.
Design Strategy
An object-oriented system may use an abstract base class to provide an appropriate, common, standardized interface for all external applications. Then, by inheriting the abstract base class, derived classes inherit all similar operations.
The functions provided by external applications (i.e., public functions) exist as pure virtual functions in the abstract base class. These pure virtual functions are implemented in the corresponding derived classes.
This architecture also makes it easy to add new applications to the system, even after the system has been defined.
other extensions