CPP Tutorial



C++ ABSTRACTION


Abstraction in C++

Abstraction is a core principle of Object-Oriented Programming that focuses on showing only essential features of an object while hiding the complex implementation details. It helps reduce complexity and increases efficiency by exposing only the necessary parts.

Why use Abstraction?

  • Simplifies interaction with complex systems.
  • Helps focus on what an object does rather than how it does it.
  • Improves code maintainability and modularity.

How to achieve Abstraction in C++?

Abstraction is mainly achieved using abstract classes and pure virtual functions.

Example of Abstraction:

#include <iostream>
using namespace std;

// Abstract class
class Shape {
public:
    // Pure virtual function providing interface framework
    virtual void draw() = 0;
    void info() {
        cout << "This is a shape." << endl;
    }
};

// Derived class implementing the abstract method
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() {
    Circle c;
    Rectangle r;

    c.info();    // Non-abstract method called
    c.draw();    // Abstract method implemented

    r.info();
    r.draw();

    // Shape s; // Error: Cannot instantiate abstract class

    return 0;
}
  

Output:

This is a shape.
Drawing a circle.
This is a shape.
Drawing a rectangle.

Key Points to Remember:

  • An abstract class contains at least one pure virtual function.
  • Pure virtual functions are declared by assigning 0, e.g., virtual void func() = 0;.
  • You cannot create objects of abstract classes directly.
  • Derived classes must provide implementations for all pure virtual functions.
  • Abstraction helps in designing interfaces and hiding implementation details.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review