Skip to content

Abstract Class vs Interface

Important Note: C++ has no interface keyword (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 class

Interface 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 ClassInterface
Pure virtualAt least oneAll methods
Concrete methodsAllowedNot allowed
Data membersAllowedNot allowed
ConstructorAllowedNot needed
Multiple inheritDiamond problem riskSafe
PurposePartial base implementationPure 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++JavaPython
Abstract classvirtual f() = 0abstract keywordABC module
InterfaceAll pure virtualinterface keywordAll @abstractmethod
Multiple interfaceYesYesYes

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."