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! šÆ
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.
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:
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.
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:
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 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.
#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;
}