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
    COMP2111
    Progress0 / 23 topics
    Topics
    1. Introduction to object oriented design2. History and advantages of object oriented design3. Introduction to object oriented programming concepts4. Classes and objects5. Data encapsulation6. Constructors and destructors7. Access modifiers8. Const vs non-const functions9. Static data members & functions10. Function overloading11. Operator overloading12. Identification of classes and their relationships13. Composition and aggregation14. Inheritance15. Multiple inheritance16. Polymorphism17. Abstract classes and interfaces18. Generic programming concepts19. Function & class templates20. Standard template library21. Object streams22. Data and object serialization using object streams23. Exception handling
    COMP2111›Abstract classes and interfaces
    Object Oriented ProgrammingTopic 17 of 23

    Abstract classes and interfaces

    7 minread
    1,125words
    Intermediatelevel

    Abstract Classes and Interfaces in C++

    In Object-Oriented Programming (OOP), both abstract classes and interfaces are used to define a contract for derived classes, but they have different purposes and characteristics. Let's dive into each one and their usage in C++.


    Abstract Classes

    An abstract class is a class that cannot be instantiated on its own and is meant to be a base class for other classes. It typically contains one or more pure virtual functions (i.e., functions that have no implementation in the abstract class itself) which must be overridden in derived classes. The purpose of an abstract class is to define common behavior that can be shared among its derived classes while leaving certain functionality to be implemented by those derived classes.

    Key Characteristics of Abstract Classes:

    1. Cannot be instantiated:

      • You cannot create objects of an abstract class directly. It serves only as a base class for other classes.
    2. Pure Virtual Functions:

      • A pure virtual function is a function declared in the abstract class that has no definition (body). It is meant to be overridden in derived classes.
      • Syntax: virtual void functionName() = 0;
    3. Can have concrete functions:

      • In addition to pure virtual functions, an abstract class can have regular (concrete) member functions with implementations.

    Syntax of an Abstract Class:

    class AbstractClass {
    public:
        // Pure virtual function (no implementation)
        virtual void pureVirtualFunction() = 0;
    
        // Regular (concrete) function with implementation
        void regularFunction() {
            cout << "This is a concrete function." << endl;
        }
    };
    

    Example of Abstract Class:

    #include <iostream>
    using namespace std;
    
    // Abstract class
    class Shape {
    public:
        // Pure virtual function
        virtual void draw() = 0;  // Derived classes must implement this
    
        // Concrete function
        void display() {
            cout << "Displaying the shape." << endl;
        }
    };
    
    // Derived class 1
    class Circle : public Shape {
    public:
        // Implementation of the pure virtual function
        void draw() override {
            cout << "Drawing a Circle." << endl;
        }
    };
    
    // Derived class 2
    class Square : public Shape {
    public:
        // Implementation of the pure virtual function
        void draw() override {
            cout << "Drawing a Square." << endl;
        }
    };
    
    int main() {
        // Shape shape; // Error: Cannot instantiate abstract class
        Shape* shape1 = new Circle();
        Shape* shape2 = new Square();
    
        shape1->draw();  // Output: Drawing a Circle.
        shape2->draw();  // Output: Drawing a Square.
        shape1->display(); // Output: Displaying the shape.
    
        delete shape1;
        delete shape2;
    
        return 0;
    }
    

    Explanation:

    • Shape is an abstract class because it contains the pure virtual function draw().
    • Circle and Square are derived classes that override the draw() function.
    • The display() function in Shape is a regular function with implementation, and it can be used by all derived classes.

    Interfaces in C++

    In C++, interfaces are usually implemented using abstract classes that contain only pure virtual functions and no data members or concrete methods. Technically, there is no specific interface keyword in C++, as there is in other languages like Java. However, an interface in C++ is typically just an abstract class that only contains pure virtual functions, and its sole purpose is to define a contract that must be followed by derived classes.

    Key Characteristics of Interfaces:

    1. Purely abstract:

      • An interface only contains pure virtual functions. It does not provide any implementations for the methods. All methods in an interface must be implemented by the derived class.
    2. No data members:

      • Typically, interfaces do not have any data members or instance variables. Their main purpose is to define behavior, not data.
    3. No concrete methods:

      • All functions in an interface are purely virtual, so they don't provide any method implementation in the interface itself.
    4. Multiple inheritance:

      • Since C++ allows multiple inheritance, an object can implement multiple interfaces, which is useful in designing flexible and reusable code.

    Syntax of an Interface:

    class InterfaceName {
    public:
        virtual void functionName() = 0;  // Pure virtual function
        virtual void anotherFunction() = 0;  // Another pure virtual function
    };
    

    Example of an Interface:

    #include <iostream>
    using namespace std;
    
    // Interface (abstract class with only pure virtual functions)
    class Drawable {
    public:
        virtual void draw() = 0;  // Pure virtual function
    };
    
    // Interface (abstract class with only pure virtual functions)
    class Resizeable {
    public:
        virtual void resize() = 0;  // Pure virtual function
    };
    
    // A class implementing both Drawable and Resizeable interfaces
    class Rectangle : public Drawable, public Resizeable {
    public:
        void draw() override {
            cout << "Drawing a Rectangle." << endl;
        }
    
        void resize() override {
            cout << "Resizing the Rectangle." << endl;
        }
    };
    
    int main() {
        Rectangle rect;
        rect.draw();   // Output: Drawing a Rectangle.
        rect.resize(); // Output: Resizing the Rectangle.
    
        return 0;
    }
    

    Explanation:

    • Drawable and Resizeable are interfaces (abstract classes containing only pure virtual functions).
    • Rectangle implements both the Drawable and Resizeable interfaces by providing concrete implementations of the draw() and resize() methods.

    Abstract Class vs. Interface

    Feature Abstract Class Interface
    Purpose Used for shared functionality and behavior among derived classes. Defines a contract that classes must implement.
    Methods Can have both pure virtual and concrete (implemented) methods. Can only have pure virtual functions (no implementations).
    Data Members Can have data members and member functions. Typically does not have data members.
    Multiple Inheritance C++ supports multiple inheritance, so you can inherit from multiple abstract classes. C++ allows implementing multiple interfaces (abstract classes with only pure virtual functions).
    Use Case Used when you need to share common functionality across multiple classes, but allow for customization in derived classes. Used when you need to enforce that certain classes must provide specific behavior (method implementation).

    Summary:

    1. Abstract Class:

      • An abstract class is a class that cannot be instantiated directly. It contains pure virtual functions (functions without implementation) that must be overridden in derived classes.
      • It can also contain regular functions with implementations.
      • Used when you want to provide common functionality to derived classes, but leave some functionality to be defined in derived classes.
    2. Interface (Abstract Class with Pure Virtual Functions):

      • An interface in C++ is essentially an abstract class that only contains pure virtual functions and no implementation or data members.
      • It is used to define a contract or interface that derived classes must follow. Every method in an interface must be implemented by the class that inherits from the interface.
      • Multiple interfaces can be implemented by a single class in C++.

    Both abstract classes and interfaces help in achieving abstraction in OOP, ensuring that certain behaviors are defined and implemented in a specific way by derived classes, while leaving other details to be handled later.

    Previous topic 16
    Polymorphism
    Next topic 18
    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,125
      Code examples0
      DifficultyIntermediate