C++ Abstraction

Abstraction is an object-oriented programming concept in C++ that focuses on hiding the internal implementation details of a class and exposing only the essential features to the user. It helps in reducing complexity and increasing code maintainability.

How Abstraction is Achieved

  • Abstract classes cannot be instantiated directly.
  • Pure virtual functions enforce derived classes to provide their own implementation.
  • Abstraction helps in separating what an object does from how it does it.

Next Topic

Next, learn about Templates in C++.

  • Through abstract classes that contain at least one pure virtual function.
  • Pure virtual functions are declared using the syntax virtual return_type functionName(parameters) = 0;.
  • Derived classes must provide implementations for all pure virtual functions to create concrete objects.

Syntax

class AbstractClass {
public:
    virtual void display() = 0; // Pure virtual function
};

class Derived : public AbstractClass {
public:
    void display() override {
        // Implementation of pure virtual function
    }
};

Example: Abstraction Using Abstract Class

#include <iostream>
using namespace std;

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

// Derived class
class Rectangle : public Shape {
private:
    int length;
    int width;

public:
    Rectangle(int l, int w) {
        length = l;
        width = w;
    }

    void area() override {
        cout << "Area of Rectangle: " << length * width << endl;
    }
};

int main() {
    Rectangle r1(5, 10);
    r1.area(); // Calls implemented function in derived class

    return 0;
}

Output

Area of Rectangle: 50

Important Notes

  • Abstract classes cannot be instantiated directly.
  • Pure virtual functions enforce derived classes to provide their own implementation.
  • Abstraction helps in separating what an object does from how it does it.

Next Topic

Next, learn about Templates in C++.