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.
Abstraction is mainly achieved using abstract classes and pure virtual functions.
#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;
}
abstract class contains at least one pure virtual function.virtual void func() = 0;.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!