ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Object Oriented Programming
    CC-211
    Progress0 / 24 topics
    Topics
    1. Object-Oriented Design: History and Advantages2. Object-Oriented Programming: Terminology and Features3. Classes and Objects4. Data Encapsulation5. Constructors and Destructors6. Access Modifiers7. Const vs Non-Const Functions8. Static Data Members and Functions9. Function Overloading10. Operator Overloading11. Identification of Classes and Their Relationships12. Composition13. Aggregation14. Inheritance15. Multiple Inheritances16. Polymorphism17. Abstract Classes18. Interfaces19. Generic Programming Concepts20. Function Templates21. Class Templates22. Standard Template Library23. Object Streams: Data and Object Serialization24. Exception Handling
    CC-211›Interfaces
    Object Oriented ProgrammingTopic 18 of 24

    Interfaces

    7 minread
    1,186words
    Intermediatelevel

    Interfaces in C++

    In C++, the concept of an interface is not a built-in feature like in some other languages (e.g., Java or C#), but it can be achieved using abstract classes. An interface in C++ is typically represented as a class that has only pure virtual functions and no data members or implemented functions. This ensures that the derived classes are forced to implement the methods defined in the interface.

    While an abstract class can have both pure virtual functions and regular member functions, an interface is typically a class that only contains pure virtual functions and no data members or concrete (implemented) functions.

    Key Features of an Interface in C++

    • Pure Virtual Functions: An interface in C++ is a class that contains only pure virtual functions. These are functions declared with = 0 at the end of the function declaration, and they have no implementation in the interface itself.

    • No Data Members: An interface class should not contain any data members (variables), as it is meant to specify behavior (i.e., method signatures), not state.

    • No Concrete Methods: Unlike abstract classes, interfaces typically do not have any concrete methods with implemented code. All functions in an interface are pure virtual functions.

    • Inheritance: Any class that wants to implement the interface must inherit from it and provide concrete implementations of the pure virtual functions.

    • Multiple Inheritance: In C++, a class can inherit from multiple interfaces, which allows a class to implement more than one set of behaviors (interfaces).

    Syntax of an Interface in C++

    class IInterface {
    public:
        // Pure virtual function (Interface method)
        virtual void method1() = 0;
        virtual void method2() = 0;
    
        // Destructor (optional, if needed)
        virtual ~IInterface() = default;
    };
    

    Implementing an Interface in C++

    A class that implements an interface must provide concrete implementations for all the pure virtual functions declared in the interface. If the class fails to do so, it will also be considered an abstract class and cannot be instantiated.

    class MyClass : public IInterface {
    public:
        // Implementing method1 from IInterface
        void method1() override {
            cout << "method1 implementation" << endl;
        }
    
        // Implementing method2 from IInterface
        void method2() override {
            cout << "method2 implementation" << endl;
        }
    };
    

    Example of Interfaces in C++

    Let's walk through an example where we define an interface Drawable and then create two classes (Circle and Rectangle) that implement the Drawable interface.

    #include <iostream>
    using namespace std;
    
    // Interface (Abstract class with pure virtual functions)
    class Drawable {
    public:
        // Pure virtual function (Interface method)
        virtual void draw() = 0;
        virtual double area() = 0;
    
        // Virtual destructor (optional)
        virtual ~Drawable() = default;
    };
    
    // Class Circle implementing Drawable interface
    class Circle : public Drawable {
    private:
        double radius;
    
    public:
        Circle(double r) : radius(r) {}
    
        void draw() override {
            cout << "Drawing a Circle" << endl;
        }
    
        double area() override {
            return 3.14159 * radius * radius; // Area of circle
        }
    };
    
    // Class Rectangle implementing Drawable interface
    class Rectangle : public Drawable {
    private:
        double width, height;
    
    public:
        Rectangle(double w, double h) : width(w), height(h) {}
    
        void draw() override {
            cout << "Drawing a Rectangle" << endl;
        }
    
        double area() override {
            return width * height; // Area of rectangle
        }
    };
    
    int main() {
        // Creating objects of derived classes
        Drawable* shape1 = new Circle(5);       // Pointer of type Drawable pointing to Circle
        Drawable* shape2 = new Rectangle(4, 6); // Pointer of type Drawable pointing to Rectangle
    
        shape1->draw();   // Calls Circle's draw method
        cout << "Circle Area: " << shape1->area() << endl;
    
        shape2->draw();   // Calls Rectangle's draw method
        cout << "Rectangle Area: " << shape2->area() << endl;
    
        // Cleanup
        delete shape1;
        delete shape2;
    
        return 0;
    }
    

    Explanation:

    • Drawable Interface: The Drawable class defines the interface with two pure virtual functions: draw() and area(). These methods must be implemented by any class that inherits from Drawable.

    • Circle and Rectangle Classes: Both Circle and Rectangle classes inherit from Drawable and implement the draw() and area() methods. These classes provide their own concrete implementations for the methods defined in the interface.

    • Main Function: The main function creates pointers to the Drawable interface type, which are then assigned to objects of type Circle and Rectangle. This demonstrates polymorphism, as the correct method is called based on the actual object type (either Circle or Rectangle), not the pointer type (Drawable).

    Benefits of Using Interfaces in C++

    1. Multiple Inheritance:

      • C++ allows classes to inherit from multiple interfaces, which means a class can implement multiple behaviors. This is different from many object-oriented languages where a class can inherit from only one interface or one class.
    2. Polymorphism:

      • Interfaces promote polymorphism. You can use pointers or references to the interface type, which allows you to work with different types of objects that implement the same interface. This enables code to be more flexible and generic, where you can write functions that operate on interface pointers without needing to know the exact derived type.
    3. Separation of Interface and Implementation:

      • Using interfaces separates the definition of a service (the interface) from the implementation of the service (the concrete class). This improves code organization, maintainability, and flexibility.
    4. Improved Code Reusability and Extensibility:

      • By defining common interfaces, you can write code that works with any class implementing that interface, regardless of the class's internal implementation. This makes it easier to extend or replace parts of the system without changing the code that uses the interface.
    5. Better Design:

      • Interfaces are often used to model abstract behaviors in the system, which helps create more maintainable and extensible designs. For example, you can define an interface for logging, database access, or network communication, and then implement different concrete classes that handle these tasks.

    Limitations of Interfaces in C++

    1. No Default Behavior:

      • Unlike abstract classes, interfaces cannot provide default behavior (i.e., default method implementations). This means that every method in an interface must be explicitly implemented in the derived classes.
    2. Cannot Have Data Members:

      • Interfaces cannot hold state or data members. This makes interfaces unsuitable for situations where you need shared data or functionality that applies to multiple derived classes.
    3. Complexity with Multiple Inheritance:

      • While C++ supports multiple inheritance, this can sometimes lead to diamond problems or ambiguity, especially when classes implement multiple interfaces with the same method signatures. Care must be taken to manage these situations.

    Summary

    • In C++, interfaces are typically implemented using abstract classes with only pure virtual functions and no data members or concrete methods.
    • Interfaces allow you to define a common set of behaviors that must be implemented by derived classes, promoting polymorphism and multiple inheritance.
    • Interfaces help decouple the definition of functionality from its implementation, improving flexibility, extensibility, and maintainability.
    Previous topic 17
    Abstract Classes
    Next topic 19
    Generic Programming Concepts

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,186
      Code examples0
      DifficultyIntermediate