![]() |
VOOZH | about |
C++ doesn't have built-in functionality of interfaces like other programming languages such as Java. However, interfaces can be implemented in C++ using the abstract classes and pure virtual functions. In this article, we will learn how to implement interfaces using abstract classes in C++.
In programming, an serves as a blueprint that specifies what methods a class will have without providing any implementation details about the methods. Many programming languages like Java have built-in functionality to implement interfaces. However, in C++, there is no built-in functionality for interfaces. Instead, are used. Any class containing a is considered an abstract class. When a class inherits from an abstract base class in C++, it must override all the pure virtual functions present in the class, or else it becomes abstract itself.
Following is the syntax for defining an abstract base class in C++:
class abstractClassName {
public:
// Pure virtual function
virtual void func() = 0;
};
To implement interfaces using abstract class in C++, we can follow the below approach:
- Declare a class with at least one pure virtual function that will act as an interface for the other derived classes.
- Define the abstract class (interface):
- Create classes that inherits from the abstract base class.
- Provide separate implementations in derived classes for each pure virtual function present in the abstract base class.
- If implementation for the pure virtual function is not provided in the derived class then it will also act as a base class.
The following program demonstrates how we can implement interfaces using abstract class in C++.
Output
Undergraduate Student: Mohit Kumar, Year: 3, Major: Computer Science
Graduate Student: Rohit Kumar, Program: Master of Science, Thesis: AI
Time Complexity: O(1)
Auxiliary Space: O(1)
Explanation: In the above example, we have declared a class Student that acts as an interface for the other two classes UndergraduateStudent and GraduateStudent which are inherited from it. The class Student is an abstract base class having two pure virtual functions getSudentInfo and printStudentInfo. Both the inherited classes have provided separate implementation for the pure virtual functions present in the interface student.
You can also go through these articles to improve your knowledge about interfaces and abstract classes: