Menu
Interfaces in C++ (Pure Virtual Functions)

Interfaces in C++ (Pure Virtual Functions)

πŸŽ₯ C++ Interfaces & Pure Virtual Functions: Complete Guide | Playlist

Playlist Link: C++ Series by TheCherno


πŸ“š Introduction to Pure Virtual Functions

Video Reference: Start at 0:00
Pure virtual functions (marked with = 0) create interfaces in C++. They:

  1. Force subclasses to implement the function.
  2. Make the base class uninstantiable (abstract class).

πŸ› οΈ Why Use Pure Virtual Functions?

  • Define contracts for subclasses (e.g., β€œAll Printable objects MUST have GetClassName”).
  • Replace Java/C#-style interface keywords (C++ uses classes).

🧩 Example: Base Class as Interface

Video Reference: 1:38

// Interface (Pure Virtual Base Class)  
class Printable {  
public:  
    virtual std::string GetClassName() = 0; // ❗ Pure virtual  
};  

class Entity : public Printable {  
public:  
    std::string GetClassName() override { return "Entity"; } // βœ… Must implement  
};  

class Player : public Entity {  
public:  
    // ❌ Compile ERROR if not overridden!  
    std::string GetClassName() override { return "Player"; } // βœ…  
};  

⚠️ Key Points:

  • Instantiation Error:
    Printable p; // ❌ Error: "Cannot declare object of abstract type"  
    
  • Subclasses MUST override all pure virtual methods.

πŸ–¨οΈ Practical Use Case: Generic Print Function

Video Reference: 3:15

// Function accepting ANY Printable object  
void Print(Printable* obj) {  
    std::cout << obj->GetClassName() << std::endl;  
}  

int main() {  
    Entity* e = new Entity();  
    Player* p = new Player();  
    Print(e); // Output: "Entity"  
    Print(p); // Output: "Player"  
}  

βœ… How It Works:

  • Print() guarantees GetClassName() exists via the Printable interface.
  • Enforces polymorphism without knowing specific subclass types.

🚫 Common Pitfalls

  1. Forgetting to Implement Pure Virtual Methods:
    class Enemy : public Printable {  
        // ❌ MISSING GetClassName() implementation  
    };  
    Enemy enemy; // Error: "Enemy is abstract"  
    
  2. Incorrect Override Syntax:
    class Player : public Printable {  
        std::string GetClassName() { return "Player"; } // ❌ Missing 'override'  
    };  
    

πŸ“Œ Key Takeaways

  1. Pure Virtual Functions:
    • Define with = 0 to create interfaces.
    • Force subclass implementation.
  2. Use Cases:
    • Enforcing method contracts (e.g., serialization, logging).
    • Polymorphic behavior without default implementations.

πŸ”— Full Video: Interfaces in C++ (Pure Virtual Functions)


Need to revisit a concept? Jump directly to the video sections with the timestamped links above! πŸš€