Menu
Virtual Functions in C++

Virtual Functions in C++

πŸŽ₯ C++ Virtual Functions

Playlist Link: C++ Series by TheCherno


πŸ“š Introduction to Virtual Functions

Video Reference: Start at 0:00
Virtual functions enable polymorphism in C++. They allow subclasses to override base class methods, ensuring the correct function is called at runtime, even when using base class pointers.

πŸ› οΈ Why Use Virtual Functions?

  • Resolve incorrect method calls when using polymorphism (e.g., treating a Player as an Entity).
  • Enable dynamic dispatch via a vtable (virtual method table).

🧩 Example: Base Class (Entity) Without Virtual

Video Reference: 2:02

class Entity {  
public:  
    std::string GetName() { return "Entity"; } // ❌ Not virtual  
};  

class Player : public Entity {  
private:  
    std::string m_Name;  
public:  
    Player(const std::string& name) : m_Name(name) {}  
    std::string GetName() { return m_Name; } // ❌ Override not enforced  
};  

// Usage:  
Entity* entity = new Player("Cherno");  
std::cout << entity->GetName(); // Prints "Entity" (WRONG!)  

Problem: Without virtual, the base class method is called, ignoring the subclass implementation.


πŸ”„ Fixing with Virtual Functions

Video Reference: 4:04

class Entity {  
public:  
    virtual std::string GetName() { return "Entity"; } // βœ… Mark as virtual  
};  

class Player : public Entity {  
private:  
    std::string m_Name;  
public:  
    Player(const std::string& name) : m_Name(name) {}  
    std::string GetName() override { return m_Name; } // βœ… Use 'override'  
};  

// Usage:  
Entity* entity = new Player("Cherno");  
std::cout << entity->GetName(); // Prints "Cherno" (CORRECT!)  

βœ… Key Points:

  1. virtual in the base class enables dynamic dispatch.
  2. override in derived classes (C++11+):
    • Improves readability.
    • Prevents typos/errors (e.g., GetName vs Getname).

βš™οΈ Runtime Costs of Virtual Functions

Video Reference: 5:26

  1. Memory Overhead:
    • Each object stores a vtable pointer (8 bytes on 64-bit systems).
  2. Performance Overhead:
    • Indirect function call via vtable (~1-2 CPU cycles).

🚨 When to Avoid Virtual Functions:

  • Ultra-low-latency systems (e.g., embedded devices).
  • In hot loops where every cycle counts (rare in most applications).

πŸ“Œ Key Takeaways

  1. Use virtual for methods needing polymorphic behavior.
  2. Always use override in derived classes for safety/clarity.
  3. Virtual functions are low-cost for most applications.

πŸ”— Full Video: Virtual Functions in C++


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