π₯ 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
Playeras anEntity). - 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:
virtualin the base class enables dynamic dispatch.overridein derived classes (C++11+):- Improves readability.
- Prevents typos/errors (e.g.,
GetNamevsGetname).
βοΈ Runtime Costs of Virtual Functions
Video Reference: 5:26
- Memory Overhead:
- Each object stores a vtable pointer (8 bytes on 64-bit systems).
- 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
- Use
virtualfor methods needing polymorphic behavior. - Always use
overridein derived classes for safety/clarity. - 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! π
