C++ Interfaces - C++ Programming Tutorial
C++ Course / Miscellaneous / C++ Interfaces

C++ Interfaces

BLUF: Mastering C++ Interfaces is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: C++ Interfaces

C++ is renowned for its efficiency. Learn how C++ Interfaces enables low-level control and high-performance computing in the tutorial below.

In C++, an interface serves as an abstract concept defining a collection of functions that are obligatory for any class declaring adherence to the Interface. It functions as a guide ensuring uniform behavior across its implementers while concealing the specifics of the concrete realization. This practice helps boost the organization, manageability, and recyclability of code, perfectly in line with the core tenets of object-oriented programming.

Although C++ does not have a designated interface keyword, the concept of an interface is achieved by utilizing abstract classes and pure virtual functions. Abstract classes contain one or more pure virtual functions, which are declared in the base class but not defined. These pure virtual functions act as the interface's methods, establishing the guidelines for any derived class from the abstract base.

Syntax

It has the following syntax:

Example

class InterfaceName {

public:

    virtual void function1() = 0;  //Pure Virtual Function

    virtual void function2() = 0;  //Pure Virtual Function

    virtual ~InterfaceName() {}  //Virtual destructor

};

Implementing the Interface

In C++, classes that adhere to the interface must redefine all pure virtual functions specified in the abstract base class. These classes supply the essential implementations for the interface methods, following the specified agreement.

Example

class ConcreteClass: public Interface {  

public:  

void method1() override {  

// Implementation for method1  

}  

void method2() override {  

// Implementation for method2  

}  

};

C++ Interface Example

Let's consider a scenario to demonstrate the interface in C++.

Example

Example

using namespace std;  //using namespace std

// Define the Shape interface  

class Shape {  

public:  

virtual double getArea() const = 0; // Pure virtual function for area  

virtual double getPerimeter() const = 0; // Pure virtual function for perimeter  

};  

// Implement the Interface for a Circle  

class Circle: public Shape {  

private:  

double radius;  

public:  

Circle(double r) : radius(r) {}  

double getArea() const override {  

return 3.14159265359 * radius * radius;  

}  

double getPerimeter() const override {  

return 2 * 3.14159265359 * radius;  

}  

};  

// Implement the Interface for a Rectangle  

class Rectangle: public Shape {  

private:  

double length;  

double width;  

public:  

Rectangle(double l, double w) : length(l), width(w) {}  

double getArea() const override {  

return length * width;  

}  

double getPerimeter() const override {  

return 2 * (length + width);  

}  

};  

int main() {  

// Create instances of Circle and Rectangle  

Circle circle(5.0);  

Rectangle rectangle(4.0, 6.0);    

// Calculate and display the area and perimeter of each shape  

cout << "Circle Area: " << circle.getArea() << ", Perimeter: " << circle.getPerimeter() << endl;  

cout << "Rectangle Area: " << rectangle.getArea() << ", Perimeter: " << rectangle.getPerimeter() << endl;    

return 0;  

}

Output:

Output

Circle Area: 78.5398, Perimeter: 31.4159

Rectangle Area: 24, Perimeter: 20

Explanation:

In this instance, we demonstrate how to utilize abstract classes to implement an interface. Here, we illustrate a Shape class acting as an interface, containing pure virtual functions like getArea and getPerimeter, which are implemented in the Circle and Rectangle classes. Each shape calculates its area and perimeter based on its specific dimensions. Within the main function, we create instances of both shapes and display the computed area and perimeter values.

Characteristics of the Interface in C++

There are several characteristics of the interface in C++. Some of them are as follows:

  • Pure virtual functions: A pure virtual interface is a class with only pure virtual functions (those declared with = 0 in the definition), in other words, pure virtual functions do not have a definition in the interface declaration.
  • It cannot be instantiated: The interface class is abstract and cannot be directly initialized due having at least one pure virtual function.
  • Implemented via Inheritance: A class is inherited through interface and all the pure virtual functions are overridden to implement a particular behaviour.
  • Virtual Destructor: It is generally a virtual destructor since the correct cleaning of its derived objects when the object is removed using the base class pointer should be appropriately done.
  • No data member: In the majority of cases the interface has no data members. These are to define behaviour and not to hold information.
  • Supports polymorphism: Polymorphism is supported by interface runtime that provides dynamic binding of methods and flexible codes.
  • Multiple interface inheritance C ++ allows a class to apply several interfaces by inheriting multiple abstract classes.
  • Benefits of C++ Interfaces:

Several benefits of C++ interfaces are as follows:

  • Consistency and Contract: Interfaces make sure that classes have the same interface and consistent behaviour. Such an arrangement resembling the contract is useful to discourage violations of the anticipated functionality, which has an enormous significance in ensuring code reliability.
  • Modularity and Separation of Concerns: The interfaces promote separation of Interface and implementation. This segregation enhances modularity of the code making it easier to handle complex systems.
  • Polymorphism and Flexibility: Interfaces help in supporting polymorphism where different classes can be treated in a consistent manner by relying on shared methods with the interface methods. It allows us to open-source our code so that it is generic, and use it with unknown flavors of implementation.
  • Testing and Mocking: Interfaces are easy to unit test and mock since we can mock interfaces implementations to allow testing of isolated parts during unit testing. It assists in detecting problems at an early development stage.
  • Code Documentation: It is inherent to the nature of interfaces to document how classes are supposed to behave. By inspecting the interface methods, developers gain insights into the functionality without delving into implementation intricacies.
  • Pure Virtual Function

In C++, a pure virtual function is a method defined in a base class without any concrete implementation, indicated by "= 0" in its declaration. It acts as an agreement that subclasses are obligated to provide an implementation for.

Syntax

It has the following syntax:

Example

virtual void myFunction() = 0;
  • "virtual": It indicates that this function is virtual, which allows polymorphism.
  • "void": It specifies the return type.
  • "myFunction": It represents the name of the function.
  • "= 0": It represents pure virtual, which means that it has no implementation in the base class and must be overridden in derived classes.
  • C++ Abstract class

In C++, a class is abstracted by specifying at least one of its functions as a pure virtual function. The "= 0" syntax is employed in the declaration of a pure virtual function, subsequently requiring the derived classes to supply its implementation.

C++ Abstract Class Example

Let's examine an abstract class in C++ containing a single abstract method, draw. Subclasses such as Rectangle and Circle are responsible for supplying their unique implementations.

Example

Example

#include <iostream>  

using namespace std;    //using standard namespace

class Shape  

{  

public:  

virtual void draw()=0;  

};  

class Rectangle: Shape  

{  

public:  

void draw()  

{  

cout <<"drawing rectangle..." <<endl;  

}  

};  

class Circle: Shape  

{  

public:  

void draw()  

{  

cout <<"drawing circle..." <<endl;  

}  

};  

int main( ) {  

Rectangle rec;  

Circle cir;  

rec.draw();  

cir.draw();  

return 0;  

}

Output:

Output

drawing rectangle...

drawing circle...

Explanation:

Here, we utilize pure virtual functions to declare an abstract class Shape, which is then extended by all the derived classes, each inheriting a draw method. Subsequently, Rectangle and Circle redefine this method to specify their respective drawing actions. On line 14 within the main function, we create instances of these derived classes and call their draw method, demonstrating polymorphism during program execution.

Real-World Use Cases

C++ interfaces are commonly utilized in practical scenarios. For example, a GUI framework may consist of various button types like simple, toggle, and radio buttons, each with shared functionalities such as initiating a click event. This is accomplished by establishing an interface outlining the button behaviors, ensuring that all button variants possess the necessary methods for consistent functionality.

Similarly, interfaces can define the behaviors of various elements in a game such as characters, enemies, and items, within the game engine's structure. This level of abstraction allows developers to incorporate new entities with distinct functionalities by implementing the required interface methods.

Rules for Using Interfaces

There are several essential rules for using interfaces in C++. Some of them are as follows:

  • Use Abstract Classes: Define interfaces as abstract classes with pure virtual functions.
  • Prefix Interface Names: Consider prefixing interface names with 'I' or similar to indicate their role.
  • No Member Data: Interfaces should not contain member data (attributes).
  • Public Access: Declare interface methods as public for external usage.
  • Explicit virtual and override: Use virtual when overriding, and override to indicate explicit overriding.
  • Implement All Methods: Any class that implements an interface is required to inherit all methods of the interface.
  • Keep It Focused: Interface methods should correlate to a theme or purpose.
  • Document Interfaces: Documents how interfaces will be used and what their purpose is.
  • Consider Segregation: Do not force classes to employ methods unrelated with them (Interface Segregation Principle).
  • Stable Interfaces: Do not add breaking change to interfaces already in use.
  • Conclusion

In summary, the implementation of a C++ interface typically involves the use of abstract classes. These classes must have at least one pure virtual function, allowing developers to define a set of requirements that derived classes must adhere to. This approach facilitates polymorphism and loose coupling in object-oriented design. By utilizing interfaces effectively, codebases can become more manageable, adaptable, and scalable, especially in complex systems and frameworks.

C++ Interface MCQs

1) Which of the following statements about the C++ interface is true?

  • C++ has an built-in interface keyword
  • Only one class can implement an interface
  • C++ interfaces are usually abstract classes with pure virtual functions
  • Interfaces cannot be found inherited

Option c) In C++, interfaces are typically represented by abstract classes that contain pure virtual functions.

2) Why can a developer choose to use an interface (abstract class) instead of a concrete base class in C++?

  • To reduce compilation time
  • To avoid virtual functions
  • To apply a contract to derived classes
  • To prevent object slicing

3) Can C++ have constructors in an abstract class?

  • No, the constructors are not allowed in the interface
  • Yes, but they are called only through derived classes
  • Yes, and abstract classes can be instantiated
  • No, only stable methods are allowed in abstract classes

Yes, however, they can only be accessed through classes that inherit from them.

4) Can an abstract class in C++ have both pure virtual and non-virtual functions?

  • Yes, it can mix pure virtual and regular member functions
  • No, all functions should be virtual
  • No, there may be no implementation in the interface
  • only when it is a templated class

a) Absolutely, it is possible to combine pure virtual functions with standard member functions.

5) How can we use the C++ interface to achieve multiple inheritances of behaviour?

  • By using stable base classes
  • By only using a template
  • It is not possible in C++
  • By inheriting many abstract classes

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience