An abstract class is a class that cannot be instantiated directly. It may contain pure virtual functions, which are functions that are declared in the abstract class but do not have an implementation.
About abstract classes
1. A function in an abstract class is made “pure virtual” by assigning = 0 at the end of its declaration. This makes the class abstract and forces derived classes to implement this function.
2. You cannot create objects of an abstract class directly. You can only create objects of derived classes that provide implementations for all pure virtual functions.
3. Abstract class is used for Inheritance.
Example:
#include <iostream>
using namespace std;
class Shape {
public:
// Pure virtual function
virtual void draw() = 0;
// Regular function
void about() {
cout << "This is a shape.\n";
}
};
class Circle : public Shape {
public:
// Providing implementation for pure virtual function
void draw() override {
cout << "Drawing Circle\n";
}
};
class Rectangle : public Shape {
public:
// Providing implementation for pure virtual function
void draw() override {
cout << "Drawing Rectangle\n";
}
};
int main() {
// Shape shape; // Error: Cannot instantiate an abstract class
// Create objects of derived classes
Circle circle;
Rectangle rectangle;
// Call function
circle.draw(); // Output: Drawing Circle
rectangle.draw(); // Output: Drawing Rectangle
return 0;
}
Explanation:
- Shape is an abstract class because it has a pure virtual function draw().
- Both Circle and Square are derived classes that implement the draw() function.
- We cannot create an instance of Shape directly, but we can create instances of Circle and Square.
Output:
Drawing Circle
Drawing Rectangle
Drawing Rectangle