Abstraction Using C++
Abstraction Using C++
Abstraction in C++ is a concept that involves hiding the complex implementation details of a
system and exposing only the necessary parts. It allows you to manage complexity by separating
the interface (what something does) from the implementation (how it does it).
Let's look at a very simple example to understand abstraction in C++.
#include <iostream>
#include <cmath> // For M_PI
int main() {
// Creating objects of Rectangle and Circle
Rectangle rect(5.0, 3.0);
Circle circ(4.0);
return 0;
}
Explanation:
5. Main Function:
```cpp
int main() {
Rectangle rect(5.0, 3.0);
Circle circ(4.0);
printArea(rect);
printArea(circ);
return 0;
}
```
- We create objects of `Rectangle` and `Circle` and pass them to the `printArea` function.
- The `printArea` function calls the appropriate `area()` method based on the actual object type,
demonstrating polymorphism.
Key Points:
- Abstraction: The user of the `Shape` class doesn't need to know the details of how the area is
calculated for different shapes.
- Polymorphism: The same function call to `area()` behaves differently based on the object type
(rectangle or circle).
- Encapsulation: The implementation details (like `width`, `height`, `radius`) are hidden inside
the derived classes.
This example shows how abstraction helps in managing complexity by focusing on what
operations an object can perform rather than how these operations are implemented.
P.S:
If you declare a function as virtual in a class but do not make it a pure virtual function (i.e., you
do not set it equal to zero), the class does not become abstract. The class can still be instantiated
because a virtual function only means that the function can be overridden in derived classes, not
that it must be.