1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M8 Runtime Poly
45% OFFBLACK FRIDAY SALE
Sale ends in
02Days
16Hrs
26Mins
20Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M8 Runtime Poly

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

02Days
16Hrs
26Mins
20Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
IntroductionEnvironment SetupSyntax & StructureOutput (cout)Comments
Variables & ConstantsData TypesType ModifiersInput (cin)Basic OperatorsLogical & BitwiseType Casting
If...ElseSwitch StatementTernary OperatorWhile & Do-While LoopsFor LoopBreak & Continue
ArraysMulti-Dimensional ArraysC-Style Stringsstd::stringStructsEnums
FunctionsParametersReturn ValuesPass by ReferenceDefault ArgumentsOverloadingInline FunctionsRecursion
Memory AddressesPointersDereferencingPointers & ArraysPointer ArithmeticDynamic MemoryReferences
OOP IntroClasses & ObjectsAccess ModifiersClass MethodsConstructorsDestructorsEncapsulation, Getters & Setters
InheritanceInheritance ConstructorsPolymorphismOperator OverloadingRuntime Poly (Virtual)Abstract ClassesFriend FunctionsThe 'this' Pointer
STL IntroSequence ContainersAssociative ContainersUnordered ContainersContainer AdaptersIteratorsAlgorithms
ExceptionsTry/CatchCatch Allstd::exceptionFile StreamsReading Files & EOF
Templates (Generics)Smart PointersLambdasPreprocessorNamespaces
C++

Runtime Poly (Virtual)

Overview

If you have an array of Animal* pointers, and you throw a Dog and a Cat into it, looping through and calling ->speak() will disastrously just call the generic Animal::speak() function. The compiler only sees the Pointer type (Animal), so it blindly executes the Animal code.

To achieve true Runtime Polymorphism, you must declare the parent's function as `virtual`. The virtual keyword forces the compiler to build a hidden 'vTable' (Virtual Table) in memory. When the program runs, the CPU checks this table dynamically, realizes the pointer is secretly holding a Dog, and executes the Dog's specific, Overridden function instead.

Syntax

cpp
#include <iostream>

class Animal {
public:
    // 1. VIRTUAL KEYWORD
    // Tells the compiler: "Wait until runtime to see what this really is!"
    virtual void speak() {
        std::cout << "Generic Animal Sound\n";
    }
};

class Dog : public Animal {
public:
    // 2. OVERRIDE KEYWORD (Optional, but highly recommended for safety)
    void speak() override {
        std::cout << "Bark!\n";
    }
};

int main() {
    // A Parent Pointer physically holding a Child Object!
    Animal* myPet = new Dog();
    
    // Because of 'virtual', the CPU dynamically routes this to Dog::speak()
    myPet->speak(); // Prints "Bark!"
    
    delete myPet;
    return 0;
}

Common Pitfalls

  • Forgetting the virtual Destructor. If you use polymorphic pointers (Animal* p = new Dog();), and you call delete p;, the CPU will only execute the Animal destructor. The Dog destructor is ignored, causing massive memory leaks. You MUST declare virtual ~Animal() in the parent class to fix this.

Interview Questions

What does the override keyword specifically do in C++11, and why is it considered mandatory in modern engineering?

The override keyword does not change how the code runs. It is a strict directive to the Compiler. It verifies that you are actually overriding a valid virtual function from the Parent. If you misspell the function name (e.g., speek()), the compiler will instantly throw a fatal error instead of silently creating a brand new function.

Real-World Example

Using polymorphic arrays to process hundreds of different game entities using a single loop.

example
cpp
#include <iostream>
#include <vector>

class Entity {
public:
    virtual void update() { std::cout << "Entity updated.\n"; }
};

class Player : public Entity {
public:
    void update() override { std::cout << "Player physics applied.\n"; }
};

class Bomb : public Entity {
public:
    void update() override { std::cout << "Bomb tick down!\n"; }
};

int main() {
    // Array of Parent Pointers!
    std::vector<Entity*> world;
    world.push_back(new Player());
    world.push_back(new Bomb());
    
    // The CPU dynamically figures out what each object is at runtime!
    for (Entity* e : world) {
        e->update();
    }
    
    return 0;
}

Check Your Knowledge

Test your understanding of Runtime Poly (Virtual) with these quick questions.

Question 1

To achieve Runtime Polymorphism in C++, how MUST the object be passed or stored?

Take C++ Quiz
Outline
IntroductionEnvironment SetupSyntax & StructureOutput (cout)Comments
Variables & ConstantsData TypesType ModifiersInput (cin)Basic OperatorsLogical & BitwiseType Casting
If...ElseSwitch StatementTernary OperatorWhile & Do-While LoopsFor LoopBreak & Continue
ArraysMulti-Dimensional ArraysC-Style Stringsstd::stringStructsEnums
FunctionsParametersReturn ValuesPass by ReferenceDefault ArgumentsOverloadingInline FunctionsRecursion
Memory AddressesPointersDereferencingPointers & ArraysPointer ArithmeticDynamic MemoryReferences
OOP IntroClasses & ObjectsAccess ModifiersClass MethodsConstructorsDestructorsEncapsulation, Getters & Setters
InheritanceInheritance ConstructorsPolymorphismOperator OverloadingRuntime Poly (Virtual)Abstract ClassesFriend FunctionsThe 'this' Pointer
STL IntroSequence ContainersAssociative ContainersUnordered ContainersContainer AdaptersIteratorsAlgorithms
ExceptionsTry/CatchCatch Allstd::exceptionFile StreamsReading Files & EOF
Templates (Generics)Smart PointersLambdasPreprocessorNamespaces
C++

Runtime Poly (Virtual)

Overview

If you have an array of Animal* pointers, and you throw a Dog and a Cat into it, looping through and calling ->speak() will disastrously just call the generic Animal::speak() function. The compiler only sees the Pointer type (Animal), so it blindly executes the Animal code.

To achieve true Runtime Polymorphism, you must declare the parent's function as `virtual`. The virtual keyword forces the compiler to build a hidden 'vTable' (Virtual Table) in memory. When the program runs, the CPU checks this table dynamically, realizes the pointer is secretly holding a Dog, and executes the Dog's specific, Overridden function instead.

Syntax

cpp
#include <iostream>

class Animal {
public:
    // 1. VIRTUAL KEYWORD
    // Tells the compiler: "Wait until runtime to see what this really is!"
    virtual void speak() {
        std::cout << "Generic Animal Sound\n";
    }
};

class Dog : public Animal {
public:
    // 2. OVERRIDE KEYWORD (Optional, but highly recommended for safety)
    void speak() override {
        std::cout << "Bark!\n";
    }
};

int main() {
    // A Parent Pointer physically holding a Child Object!
    Animal* myPet = new Dog();
    
    // Because of 'virtual', the CPU dynamically routes this to Dog::speak()
    myPet->speak(); // Prints "Bark!"
    
    delete myPet;
    return 0;
}

Common Pitfalls

  • Forgetting the virtual Destructor. If you use polymorphic pointers (Animal* p = new Dog();), and you call delete p;, the CPU will only execute the Animal destructor. The Dog destructor is ignored, causing massive memory leaks. You MUST declare virtual ~Animal() in the parent class to fix this.

Interview Questions

What does the override keyword specifically do in C++11, and why is it considered mandatory in modern engineering?

The override keyword does not change how the code runs. It is a strict directive to the Compiler. It verifies that you are actually overriding a valid virtual function from the Parent. If you misspell the function name (e.g., speek()), the compiler will instantly throw a fatal error instead of silently creating a brand new function.

Real-World Example

Using polymorphic arrays to process hundreds of different game entities using a single loop.

example
cpp
#include <iostream>
#include <vector>

class Entity {
public:
    virtual void update() { std::cout << "Entity updated.\n"; }
};

class Player : public Entity {
public:
    void update() override { std::cout << "Player physics applied.\n"; }
};

class Bomb : public Entity {
public:
    void update() override { std::cout << "Bomb tick down!\n"; }
};

int main() {
    // Array of Parent Pointers!
    std::vector<Entity*> world;
    world.push_back(new Player());
    world.push_back(new Bomb());
    
    // The CPU dynamically figures out what each object is at runtime!
    for (Entity* e : world) {
        e->update();
    }
    
    return 0;
}

Check Your Knowledge

Test your understanding of Runtime Poly (Virtual) with these quick questions.

Question 1

To achieve Runtime Polymorphism in C++, how MUST the object be passed or stored?

Take C++ Quiz

C++ coding notes for Indian students — 72 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in C++

  1. Introduction
  2. Environment Setup
  3. Syntax & Structure
  4. Output (cout)
  5. Comments
  6. Variables & Constants
  7. Data Types
  8. Type Modifiers
  9. Input (cin)
  10. Basic Operators
  11. Logical & Bitwise
  12. Type Casting
  13. If...Else
  14. Switch Statement
  15. Ternary Operator
  16. While & Do-While Loops
  17. For Loop
  18. Break & Continue
  19. Arrays
  20. Multi-Dimensional Arrays
  21. C-Style Strings
  22. std::string
  23. Structs
  24. Enums
  25. Functions
  26. Parameters
  27. Return Values
  28. Pass by Reference
  29. Default Arguments
  30. Overloading
  31. Inline Functions
  32. Recursion
  33. Memory Addresses
  34. Pointers
  35. Dereferencing
  36. Pointers & Arrays
  37. Pointer Arithmetic
  38. Dynamic Memory
  39. References
  40. OOP Intro
  41. Classes & Objects
  42. Access Modifiers
  43. Class Methods
  44. Constructors
  45. Destructors
  46. Encapsulation, Getters & Setters
  47. Inheritance
  48. Inheritance Constructors
  49. Polymorphism
  50. Operator Overloading
  51. Runtime Poly (Virtual)
  52. Abstract Classes
  53. Friend Functions
  54. The 'this' Pointer
  55. STL Intro
  56. Sequence Containers
  57. Associative Containers
  58. Unordered Containers
  59. Container Adapters
  60. Iterators
  61. Algorithms
  62. Exceptions
  63. Try/Catch
  64. Catch All
  65. std::exception
  66. File Streams
  67. Reading Files & EOF
  68. Templates (Generics)
  69. Smart Pointers
  70. Lambdas
  71. Preprocessor
  72. Namespaces

Study next

  • All coding notes
  • C++ notes home
  • C++ certification quiz
  • Online compiler
  • Interview Q&A

C++ coding notes for Indian students — 72 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in C++

  1. Introduction
  2. Environment Setup
  3. Syntax & Structure
  4. Output (cout)
  5. Comments
  6. Variables & Constants
  7. Data Types
  8. Type Modifiers
  9. Input (cin)
  10. Basic Operators
  11. Logical & Bitwise
  12. Type Casting
  13. If...Else
  14. Switch Statement
  15. Ternary Operator
  16. While & Do-While Loops
  17. For Loop
  18. Break & Continue
  19. Arrays
  20. Multi-Dimensional Arrays
  21. C-Style Strings
  22. std::string
  23. Structs
  24. Enums
  25. Functions
  26. Parameters
  27. Return Values
  28. Pass by Reference
  29. Default Arguments
  30. Overloading
  31. Inline Functions
  32. Recursion
  33. Memory Addresses
  34. Pointers
  35. Dereferencing
  36. Pointers & Arrays
  37. Pointer Arithmetic
  38. Dynamic Memory
  39. References
  40. OOP Intro
  41. Classes & Objects
  42. Access Modifiers
  43. Class Methods
  44. Constructors
  45. Destructors
  46. Encapsulation, Getters & Setters
  47. Inheritance
  48. Inheritance Constructors
  49. Polymorphism
  50. Operator Overloading
  51. Runtime Poly (Virtual)
  52. Abstract Classes
  53. Friend Functions
  54. The 'this' Pointer
  55. STL Intro
  56. Sequence Containers
  57. Associative Containers
  58. Unordered Containers
  59. Container Adapters
  60. Iterators
  61. Algorithms
  62. Exceptions
  63. Try/Catch
  64. Catch All
  65. std::exception
  66. File Streams
  67. Reading Files & EOF
  68. Templates (Generics)
  69. Smart Pointers
  70. Lambdas
  71. Preprocessor
  72. Namespaces

Study next

  • All coding notes
  • C++ notes home
  • C++ certification quiz
  • Online compiler
  • Interview Q&A