Mark As Completed Discussion

Abstraction

Abstraction is a fundamental concept in object-oriented programming (OOP) that allows us to model real-world objects and systems at a higher level of complexity. It involves hiding unnecessary details and focusing on the essential characteristics of an object or system.

In C++, abstraction is achieved through the use of abstract classes. An abstract class is a class that cannot be instantiated and serves as a blueprint for other classes. It contains pure virtual functions, which are functions with no implementation in the abstract class.

TEXT/X-C++SRC
1// Abstract class
2
3class Shape {
4public:
5    // Pure virtual function
6    virtual void draw() = 0;
7};

The Shape class is an example of an abstract class in C++. It contains a pure virtual function draw(), which is a function that must be overridden in derived classes. This allows for the creation of different shapes, such as circles and rectangles, that each have their own way of being drawn.

TEXT/X-C++SRC
1// Derived class
2
3class Circle : public Shape {
4public:
5    void draw() {
6        cout << "Drawing a circle" << endl;
7    }
8};
9
10// Derived class
11
12class Rectangle : public Shape {
13public:
14    void draw() {
15        cout << "Drawing a rectangle" << endl;
16    }
17};

The Circle and Rectangle classes are derived classes that inherit from the Shape class. They provide the implementation for the draw() function specific to their shape. This allows for the flexibility to create different shapes that can be treated as Shape objects.

TEXT/X-C++SRC
1int main() {
2    Shape* shape1;
3    Shape* shape2;
4
5    Circle circle;
6    Rectangle rectangle;
7
8    shape1 = &circle;
9    shape2 = &rectangle;
10
11    shape1->draw(); // Output: Drawing a circle
12    shape2->draw(); // Output: Drawing a rectangle
13
14    return 0;
15}

In the main() function, we create objects of the derived classes Circle and Rectangle and assign them to pointers of the base class type Shape. We can then call the draw() function on these pointers, and the appropriate implementation specific to each shape will be invoked.

Abstraction allows us to manage complexity, minimize duplication of code, and promote code flexibility. By focusing on the essential characteristics and hiding unnecessary details, abstraction enhances code readability and maintainability.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment