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›Abstract Classes
    Object Oriented ProgrammingTopic 17 of 24

    Abstract Classes

    6 minread
    1,018words
    Intermediatelevel

    Abstract Classes in C++

    An abstract class in C++ is a class that cannot be instantiated (i objects cannot be created from it). It serves as a blueprint for other classes. An abstract class typically contains one or more pure virtual functions (also known as abstract methods) that must be implemented by its derived classes. Abstract classes provide a way to enforce that certain methods are implemented by any class that derives from it, which is a key part of object-oriented design.

    Key Characteristics of Abstract Classes

    1. Pure Virtual Functions: An abstract class has at least one pure virtual function. A pure virtual function is declared by assigning = 0 to the function declaration. This makes the function "pure" and forces any derived class to provide its own implementation of this function.

    2. Cannot Be Instantiated: You cannot create objects of an abstract class directly. However, you can create pointers or references to an abstract class type and point them to objects of derived classes.

    3. Can Have Normal Member Functions: While abstract classes must have at least one pure virtual function, they can also have fully implemented functions, data members, and constructors.

    4. Inheritance: Derived classes must override all pure virtual functions from the abstract base class, unless they are also abstract themselves.

    Syntax of Abstract Class

    Here’s how you declare a pure virtual function and an abstract class in C++:

    class AbstractClass {
    public:
        // Pure virtual function
        virtual void pureVirtualFunction() = 0;
    
        // Normal member function
        void normalFunction() {
            cout << "This is a normal function" << endl;
        }
    };
    

    In this example:

    • The function pureVirtualFunction is a pure virtual function because it is followed by = 0.
    • The class AbstractClass is an abstract class because it contains a pure virtual function.

    Example of Abstract Class in C++

    Let’s consider an example where we define an abstract class for geometric shapes and then create derived classes like Circle and Rectangle that implement the required functionality.

    #include <iostream>
    #include <cmath>  // For M_PI
    using namespace std;
    
    // Abstract class
    class Shape {
    public:
        // Pure virtual function
        virtual void draw() = 0;  // Every shape must implement the draw function
    
        // Pure virtual function
        virtual double area() = 0;  // Every shape must implement the area function
    };
    
    // Derived class: Circle
    class Circle : public Shape {
    private:
        double radius;
    
    public:
        Circle(double r) : radius(r) {}
    
        void draw() override {
            cout << "Drawing a circle" << endl;
        }
    
        double area() override {
            return M_PI * radius * radius;  // Area of circle = πr²
        }
    };
    
    // Derived class: Rectangle
    class Rectangle : public Shape {
    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 = width * height
        }
    };
    
    int main() {
        // Creating objects of derived classes
        Shape* shape1 = new Circle(5);  // Pointer of type Shape pointing to a Circle
        Shape* shape2 = new Rectangle(4, 6);  // Pointer of type Shape pointing to a Rectangle
    
        shape1->draw();  // Calls Circle's draw method
        cout << "Area of Circle: " << shape1->area() << endl;
    
        shape2->draw();  // Calls Rectangle's draw method
        cout << "Area of Rectangle: " << shape2->area() << endl;
    
        // Cleanup
        delete shape1;
        delete shape2;
    
        return 0;
    }
    

    Explanation:

    1. Abstract Base Class (Shape):

      • The Shape class contains two pure virtual functions: draw() and area(). These functions must be overridden in any class that inherits from Shape.
    2. Derived Classes (Circle and Rectangle):

      • Both Circle and Rectangle are derived from Shape. They implement the draw() and area() methods, providing specific behavior for each type of shape.
    3. Pointer to Abstract Class:

      • We create a pointer of type Shape* and assign it to objects of derived classes (Circle and Rectangle). This demonstrates polymorphism, as the pointer can refer to any derived object that implements the pure virtual functions.
    4. Output:

      Drawing a circle
      Area of Circle: 78.5398
      Drawing a rectangle
      Area of Rectangle: 24
      

    Why Use Abstract Classes?

    1. Enforce Interface in Derived Classes: Abstract classes allow us to define a common interface that all derived classes must follow. By declaring pure virtual functions in the base class, we ensure that each derived class provides its own implementation of these functions. This is useful in situations where different objects should behave similarly (i.e., they should implement the same functions) but with different implementations.

    2. Polymorphism: Abstract classes provide a way to use polymorphism in C++. By using pointers or references to abstract classes, we can call methods in derived classes without knowing the exact type of the object at compile time. The appropriate function is chosen dynamically at runtime.

    3. Code Reusability: Abstract classes allow common functionality to be placed in the base class, while specialized functionality can be added by derived classes. This enables you to reuse code in the base class and extend it in derived classes, making code easier to maintain and more flexible.

    4. Design Flexibility: Abstract classes give a way to model real-world objects and their relationships with more flexibility. For example, you can define a general Shape class with specific types of shapes (like Circle and Rectangle) being derived from it, without having to change the client code that uses Shape pointers.

    Summary

    • An abstract class in C++ is a class that cannot be instantiated directly.
    • It typically contains pure virtual functions, which are functions that have no implementation in the base class and must be overridden in derived classes.
    • Abstract classes help enforce a consistent interface across derived classes, promote polymorphism, and code reuse.
    • Abstract classes can have both pure virtual functions (which must be overridden in derived classes) and normal member functions (with implementations).
    Previous topic 16
    Polymorphism
    Next topic 18
    Interfaces

    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 time6 min
      Word count1,018
      Code examples0
      DifficultyIntermediate