Abstraction

Abstraction is one of the core principles of object-oriented programming (OOP) in C++. It involves hiding the complex implementation details of a system and exposing only the necessary parts to the user.

Key Points

  1. Simplification: It simplifies complex systems by breaking them into smaller, manageable parts.
  2. Interface and Implementation: Focuses on what an object does rather than how it does it.
  3. Use of Classes: Classes are used to model real-world entities with relevant attributes and methods.

How to Achieve Abstraction

Abstract Classes

Defined using the class keyword.Contains pure virtual functions (methods declared but not defined).Cannot be instantiated directly.

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

Interfaces

C++ doesn’t have a distinct interface keyword, but abstract classes with only pure virtual functions act as interfaces.

class Drawable {
public:
    virtual void draw() = 0;
};

Encapsulation

By using access specifiers (public, private, protected), details of the implementation are hidden, providing a clear interface.

Function Overloading

Providing different implementations for a function name, allowing for varied input parameters.

Templates

Allow writing generic functions or classes that work with any data type, abstracting specific type details.

Example of Abstraction

#include <iostream>
#include <vector>

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

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

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

int main() {
    std::vector<Shape*> shapes;
    shapes.push_back(new Circle());
    shapes.push_back(new Rectangle());

    for (Shape* shape : shapes) {
        shape->draw(); // Calls the appropriate draw function
    }

    // Cleanup
    for (Shape* shape : shapes) {
        delete shape;
    }

    return 0;
}

Benefits of Abstraction

  1. Reduced Complexity: Users interact with simplified interfaces rather than complex implementations.
  2. Increased Security: Internal implementation details are hidden, reducing the risk of unintended interference.
  3. Improved Maintainability: Changes in implementation details do not affect external code using the interface.
  4. Flexibility: Allows changes in the internal workings without altering the external interface.