top of page
Writer's picturecompnomics

Abstract Classes in C++


An abstract class is a class that cannot be instantiated directly. It serves as a blueprint for derived classes, providing a common interface and defining the basic structure of objects. Abstract classes often contain one or more pure virtual functions.


Pure Virtual Functions

A pure virtual function is a virtual function declared with a pure specifier, = 0. It doesn't have a body and forces derived classes to provide their own implementation.


Syntax:

virtual return_type function_name() = 0;

Example:

#include <iostream>

using namespace std;

class Shape {
public:
    virtual void draw() = 0; // Pure virtual function
};

class Circle : public Shape {
public:
    void draw() override {
        cout << "Drawing a circle" << endl;
    }
};

class Rectangle : public Shape {
public:
    void draw() override {
        cout << "Drawing a rectangle" << endl;
    }
};

int main() {
    // Shape shape; // Cannot create an instance of an abstract class
    Circle circle;
    Rectangle rectangle;

    circle.draw();
    rectangle.draw();

    return 0;
}

Key Points:

  • Abstract Classes Cannot Be Instantiated: You cannot create objects of an abstract class directly.

  • Pure Virtual Functions Must Be Implemented in Derived Classes: Derived classes must provide concrete implementations for all inherited pure virtual functions.

  • Abstract Classes Promote Polymorphism: They enable you to treat objects of different derived classes as if they were objects of the base class.

  • Abstract Classes Can Have Both Pure Virtual and Non-Pure Virtual Functions: Non-pure virtual functions can have default implementations.


Advantages of Abstract Classes:

  • Enforce Polymorphism: Abstract classes ensure that derived classes implement specific methods, promoting polymorphism.

  • Define a Common Interface: They provide a blueprint for derived classes, ensuring consistency.

  • Promote Code Reusability: Abstract classes can be used to create reusable components.

  • Hide Implementation Details: They can hide the internal implementation details of derived classes.


By understanding abstract classes and pure virtual functions, you can create flexible and extensible object-oriented designs in C++.

8 views0 comments

Recent Posts

See All

Commentaires

Noté 0 étoile sur 5.
Pas encore de note

Ajouter une note
bottom of page