Appearance
Abstract Class vs Interface
Important Note: C++ has no
interfacekeyword (unlike Java). Interfaces are simulated using a class with all pure virtual functions.
Abstract Class: A class with at least one pure virtual function (= 0). Can have a mix of implemented and pure virtual methods.
Interface (in C++): A class with only pure virtual functions and no data members. Purely a contract — no implementation at all.
Abstract Class Example
cpp
class Vehicle {
int year; // data member allowed
public:
string brand;
Vehicle(string b) : brand(b) {}
virtual void start() = 0; // pure virtual — must override
virtual void stop() = 0; // pure virtual — must override
void honk() { // concrete method allowed
cout << "Beep beep!" << endl;
}
virtual ~Vehicle() {}
};
class Car : public Vehicle {
public:
Car(string b) : Vehicle(b) {}
void start() override { cout << brand << " car started" << endl; }
void stop() override { cout << brand << " car stopped" << endl; }
};
// Vehicle v; // ERROR — cannot instantiate abstract classInterface Example (Simulated in C++)
cpp
class Printable { // interface
public:
virtual void print() = 0; // only pure virtual
virtual void preview() = 0; // only pure virtual
virtual ~Printable() {} // virtual destructor
// NO data members, NO concrete methods
};Multiple Interface Implementation
cpp
class Duck : public Flyable,
public Swimmable,
public Runnable {
public:
void fly() override { cout << "Duck flying" << endl; }
void swim() override { cout << "Duck swimming" << endl; }
void run() override { cout << "Duck running" << endl; }
};Key Differences
| Abstract Class | Interface | |
|---|---|---|
| Pure virtual | At least one | All methods |
| Concrete methods | Allowed | Not allowed |
| Data members | Allowed | Not allowed |
| Constructor | Allowed | Not needed |
| Multiple inherit | Diamond problem risk | Safe |
| Purpose | Partial base implementation | Pure contract |
When to Use Which
- Use Abstract Class: sharing common implementation among related classes, classes share data members
- Use Interface: defining a contract for unrelated classes, need multiple inheritance safely
C++ vs Java vs Python
| C++ | Java | Python | |
|---|---|---|---|
| Abstract class | virtual f() = 0 | abstract keyword | ABC module |
| Interface | All pure virtual | interface keyword | All @abstractmethod |
| Multiple interface | Yes | Yes | Yes |
One-liner: "In C++, an abstract class has at least one pure virtual function and can have data/concrete methods, while an interface is simulated as a class with only pure virtual functions — acting as a pure contract with no implementation."