Abstract Class in C++
-
A class that has at least one pure virtual function.
-
Cannot be instantiated (you cannot create objects directly).
-
Can contain:
-
Normal methods (concrete) ✅
-
Virtual methods ✅
-
Pure virtual methods (abstract) ✅
-
Data members ✅
-
Example:
Copy#include <iostream>
using namespace std;
class Shape { // Abstract class
public:
virtual void draw() = 0; // pure virtual -> must be overridden
void info() { cout << "This is a shape\n"; } // normal method
};
class Circle : public Shape {
public:
void draw() override { cout << "Drawing Circle\n"; }
};
int main() {
// Shape s; ❌ Error: cannot instantiate abstract class
Shape* shape = new Circle();
shape->draw(); // "Drawing Circle"
shape->info(); // "This is a shape"
delete shape;
}
👉 Shape is abstract because it has a pure virtual method.
👉 Circle is concrete because it implements draw().
Interface in C++ (Simulated)
In Java, interface means only abstract methods (and constants).
In C++, we simulate interfaces using abstract classes with only pure virtual methods.
Example:
Copy#include <iostream>
using namespace std;
// Interface simulation
class Drawable {
public:
virtual void draw() = 0; // pure virtual
virtual void resize() = 0; // pure virtual
};
class Circle : public Drawable {
public:
void draw() override { cout << "Circle Drawn\n"; }
void resize() override { cout << "Circle Resized\n"; }
};
int main() {
Drawable* d = new Circle();
d->draw(); // Circle Drawn
d->resize(); // Circle Resized
delete d;
}
👉 Here Drawable is like an interface:
-
No concrete implementation.
-
Just method declarations (
= 0).
Difference Between Abstract Class and Interface in C++
Feature | Abstract Class | Interface (in C++ simulation) |
|---|---|---|
Methods | Can have concrete + pure virtual methods | Only pure virtual methods |
Data Members | Can have data members (variables) | Usually avoided, but can have constants |
Inheritance | Supports single + multiple inheritance | Supports multiple inheritance (common for interfaces) |
Instantiation | Cannot be instantiated | Cannot be instantiated |