Abstraction is one of the core principles of object-oriented programming (OOP) in C++. It involves hiding the complex implementation details of a system and exposing only the necessary parts to the user.
Defined using the class
keyword.Contains pure virtual functions (methods declared but not defined).Cannot be instantiated directly.
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};
C++ doesn’t have a distinct interface keyword, but abstract classes with only pure virtual functions act as interfaces.
class Drawable {
public:
virtual void draw() = 0;
};
By using access specifiers (public
, private
, protected
), details of the implementation are hidden, providing a clear interface.
Providing different implementations for a function name, allowing for varied input parameters.
Allow writing generic functions or classes that work with any data type, abstracting specific type details.
#include <iostream>
#include <vector>
// Abstract class
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};
class Circle : public Shape {
public:
void draw() override {
std::cout << "Drawing Circle" << std::endl;
}
};
class Rectangle : public Shape {
public:
void draw() override {
std::cout << "Drawing Rectangle" << std::endl;
}
};
int main() {
std::vector<Shape*> shapes;
shapes.push_back(new Circle());
shapes.push_back(new Rectangle());
for (Shape* shape : shapes) {
shape->draw(); // Calls the appropriate draw function
}
// Cleanup
for (Shape* shape : shapes) {
delete shape;
}
return 0;
}