C++ Abstraction šŸš€

beginner
11 min

C++ Abstraction šŸš€

Welcome to our deep dive into C++ Abstraction! In this lesson, we'll explore how to use abstraction to write cleaner, more efficient, and easier-to-maintain code. Let's get started! šŸŽÆ

What is Abstraction? šŸ’”

Abstraction is a programming technique that focuses on hiding the implementation details and only exposing the essential features of an object or a concept. In C++, we use classes and interfaces to achieve abstraction.

Why Use Abstraction? šŸ“

  1. Reduces complexity: By hiding the implementation details, we make the code easier to understand and maintain.
  2. Encapsulation: Abstraction helps in encapsulating data and functions together as a single unit, which promotes data hiding and prevents unauthorized access.
  3. Improved modularity: By grouping related functionality, we can create modular and reusable code components.

Creating an Abstract Class šŸŽÆ

To create an abstract class in C++, use the virtual keyword followed by the = 0 symbol. Here's an example of an abstract class representing a Shape:

cpp
class AbstractShape { public: virtual double area() = 0; // Pure virtual function };

A class with at least one pure virtual function is considered an abstract class and cannot be instantiated.

Creating Concrete Classes šŸŽÆ

Concrete classes are derived from abstract classes and provide the implementation for the pure virtual functions. Here's an example of a Circle and Rectangle class derived from the AbstractShape:

cpp
class Circle : public AbstractShape { private: double radius; public: Circle(double r) : radius(r) {} double area() override { return 3.14 * radius * radius; } }; class Rectangle : public AbstractShape { private: double length, width; public: Rectangle(double l, double w) : length(l), width(w) {} double area() override { return length * width; } };

Polymorphism šŸ’”

Polymorphism is the ability of an object to take on many forms. In C++, we can achieve polymorphism by using abstract base classes and their derived concrete classes. This allows us to write generic code that can handle different object types.

Example: A Program to Calculate the Area of Shapes šŸ“

cpp
#include <iostream> class AbstractShape { public: virtual double area() = 0; }; class Circle : public AbstractShape { private: double radius; public: Circle(double r) : radius(r) {} double area() override { return 3.14 * radius * radius; } }; class Rectangle : public AbstractShape { private: double length, width; public: Rectangle(double l, double w) : length(l), width(w) {} double area() override { return length * width; } }; int main() { Circle circle(5); Rectangle rectangle(4, 6); AbstractShape* shapes[] = {&circle, &rectangle}; for (AbstractShape* shape : shapes) { std::cout << "Area: " << shape->area() << std::endl; } return 0; }