Bird
Raised Fist0
C++programming~10 mins

Virtual functions in C++ - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Virtual functions
Create Base class pointer
↓
Assign Derived object to pointer
↓
Call virtual function
↓
Check object's actual type
↓
Call Derived's override if exists
↓
Return result
A base class pointer calls a virtual function, which runs the derived class's version if overridden.
Execution Sample
C++
#include <iostream>
using namespace std;

class Base {
public:
  virtual void show() { cout << "Base"; }
};

class Derived : public Base {
public:
  void show() override { cout << "Derived"; }
};

int main() {
  Base* ptr;
  ptr = new Derived();
  ptr->show();
  delete ptr;
  return 0;
}
Shows how a base class pointer calls the derived class's overridden virtual function.
Execution Table
StepActionPointer TypeObject TypeFunction CalledOutput
1Create Base pointerBase*NoneNone
2Assign Derived object to pointerBase*DerivedNone
3Call show() via pointerBase*DerivedDerived::show()Derived
4End of execution----
💡 Function call resolved to Derived::show() because show() is virtual and object is Derived
Variable Tracker
VariableStartAfter Step 2After Step 3Final
ptrnullpoints to Derived objectpoints to Derived objectpoints to Derived object
Key Moments - 2 Insights
Why does ptr->show() call Derived::show() even though ptr is a Base*?
Because show() is declared virtual in Base, the program checks the actual object type (Derived) at runtime and calls Derived's version (see execution_table step 3).
What if show() was not virtual? Which function would be called?
If show() was not virtual, Base::show() would be called regardless of the object type, because function calls are resolved by pointer type at compile time.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output at step 3?
ANo output
BBase
CDerived
DCompilation error
💡 Hint
Check the 'Output' column in execution_table row for step 3
At which step does the pointer start pointing to a Derived object?
AStep 2
BStep 3
CStep 1
DStep 4
💡 Hint
Look at the 'Pointer Type' and 'Object Type' columns in execution_table
If show() was not virtual, what would be the function called at step 3?
ADerived::show()
BBase::show()
CNo function called
DCompiler error
💡 Hint
Refer to key_moments explanation about virtual vs non-virtual function calls
Concept Snapshot
Virtual functions allow a base class pointer to call derived class methods at runtime.
Declare a function with 'virtual' in base class.
Override it in derived class with same signature.
Calls via base pointer use derived version if overridden.
Enables runtime polymorphism in C++.
Full Transcript
This example shows how virtual functions work in C++. We create a base class pointer and assign it a derived class object. When we call the virtual function show() through the base pointer, the program checks the actual object type at runtime. Because the object is of the derived class, the derived class's show() function runs, printing 'Derived'. This is different from normal functions, which are decided at compile time based on pointer type. Virtual functions enable this dynamic behavior, called runtime polymorphism.

Practice

(1/5)
1. What is the main purpose of declaring a function as virtual in a C++ base class?
easy
A. To allow derived classes to override the function and enable runtime polymorphism
B. To make the function inline for faster execution
C. To prevent the function from being overridden in derived classes
D. To make the function static and shared among all objects

Solution

  1. Step 1: Understand virtual function role

    A virtual function in a base class allows derived classes to provide their own implementation that will be called at runtime.
  2. Step 2: Recognize runtime polymorphism

    This mechanism enables dynamic dispatch, meaning the program decides which function to call based on the actual object type, not the pointer type.
  3. Final Answer:

    To allow derived classes to override the function and enable runtime polymorphism -> Option A
  4. Quick Check:

    Virtual function = runtime polymorphism [OK]
Hint: Virtual means choose function at runtime, not compile time [OK]
Common Mistakes:
  • Confusing virtual with inline functions
  • Thinking virtual prevents overriding
  • Assuming virtual makes function static
2. Which of the following is the correct syntax to declare a virtual function named display in a base class?
easy
A. virtual void display();
B. void virtual display();
C. virtual display void();
D. void display() virtual;

Solution

  1. Step 1: Recall correct virtual function syntax

    The keyword virtual must come before the return type and function name.
  2. Step 2: Check each option

    virtual void display(); correctly places virtual before void display();. Others have incorrect order or placement.
  3. Final Answer:

    virtual void display(); -> Option A
  4. Quick Check:

    virtual before return type = correct syntax [OK]
Hint: Put 'virtual' before return type in function declaration [OK]
Common Mistakes:
  • Placing virtual after function name
  • Mixing order of keywords
  • Adding virtual at the end of declaration
3. Consider the following code:
class Base {
public:
    virtual void show() { std::cout << "Base"; }
};
class Derived : public Base {
public:
    void show() override { std::cout << "Derived"; }
};

int main() {
    Base* ptr = new Derived();
    ptr->show();
    delete ptr;
    return 0;
}

What is the output when this program runs?
medium
A. Base
B. Runtime error
C. Derived
D. Compilation error

Solution

  1. Step 1: Analyze pointer and object types

    The pointer is of type Base* but points to a Derived object.
  2. Step 2: Understand virtual function call

    Because show() is virtual, the Derived version is called at runtime, printing "Derived".
  3. Final Answer:

    Derived -> Option C
  4. Quick Check:

    Virtual function calls derived version [OK]
Hint: Virtual calls use actual object type, not pointer type [OK]
Common Mistakes:
  • Assuming base class function runs
  • Confusing override keyword effect
  • Expecting compilation or runtime errors
4. Identify the error in the following code snippet:
class Base {
public:
    void display() { std::cout << "Base"; }
};
class Derived : public Base {
public:
    void display() override { std::cout << "Derived"; }
};
medium
A. Derived class function cannot have the same name as base class function
B. No error, code is correct
C. Override keyword is not allowed in derived class
D. Base class function must be declared virtual to allow override

Solution

  1. Step 1: Check base class function declaration

    The base class function display() is not declared virtual.
  2. Step 2: Understand override keyword usage

    The override keyword requires the base function to be virtual; otherwise, it causes a compilation error.
  3. Final Answer:

    Base class function must be declared virtual to allow override -> Option D
  4. Quick Check:

    Override needs virtual base function [OK]
Hint: Base function must be virtual to use override in derived [OK]
Common Mistakes:
  • Ignoring missing virtual in base
  • Thinking override is optional
  • Assuming same name always means override
5. Given the classes below, what will be the output of the program?
class Animal {
public:
    virtual void sound() { std::cout << "Animal sound "; }
};
class Dog : public Animal {
public:
    void sound() override { std::cout << "Bark "; }
};
class Cat : public Animal {
public:
    void sound() override { std::cout << "Meow "; }
};

int main() {
    Animal* animals[3];
    animals[0] = new Animal();
    animals[1] = new Dog();
    animals[2] = new Cat();

    for (int i = 0; i < 3; i++) {
        animals[i]->sound();
    }

    for (int i = 0; i < 3; i++) {
        delete animals[i];
    }
    return 0;
}
hard
A. Animal sound Animal sound Animal sound
B. Animal sound Bark Meow
C. Bark Meow Animal sound
D. Compilation error due to array of pointers

Solution

  1. Step 1: Analyze array of Animal pointers

    The array holds pointers to objects of types Animal, Dog, and Cat respectively.
  2. Step 2: Understand virtual function calls in loop

    Calling sound() on each pointer calls the overridden version based on actual object type, printing "Animal sound ", "Bark ", and "Meow ".
  3. Final Answer:

    Animal sound Bark Meow -> Option B
  4. Quick Check:

    Virtual calls print actual object sounds [OK]
Hint: Virtual functions call derived versions in arrays of base pointers [OK]
Common Mistakes:
  • Expecting base class sound for all
  • Confusing array pointer syntax
  • Assuming compilation error with polymorphism
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard