0
0
C++programming~5 mins

Virtual functions in C++ - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a virtual function in C++?
A virtual function is a member function in a base class that you expect to be overridden in derived classes. It allows C++ to support runtime polymorphism by deciding which function to call at runtime based on the object's actual type.
Click to reveal answer
beginner
Why do we use virtual functions?
We use virtual functions to achieve dynamic dispatch, meaning the program decides at runtime which function to call depending on the actual object type, not the pointer or reference type. This helps in writing flexible and extendable code.
Click to reveal answer
intermediate
What happens if a base class function is not declared virtual but overridden in a derived class?
If the base class function is not virtual, then calling the function through a base class pointer or reference will always call the base class version, even if the object is of a derived class. This is called static binding.
Click to reveal answer
beginner
How do you declare a virtual function in C++?
You declare a virtual function by adding the keyword virtual before the function's return type in the base class. For example:
virtual void speak();
Click to reveal answer
intermediate
What is a pure virtual function and how is it declared?
A pure virtual function is a virtual function with no implementation in the base class, making the class abstract. It is declared by assigning 0 to the function in the base class, like this: <pre>virtual void draw() = 0;</pre>
Click to reveal answer
What keyword is used to declare a virtual function in C++?
Aabstract
Boverride
Cdynamic
Dvirtual
If a base class function is virtual, which function is called when using a base class pointer to a derived object?
ABase class function
BDerived class function
CCompiler error
DDepends on pointer type
What happens if you call a non-virtual function through a base class pointer to a derived object?
ABase class function is called
BDerived class function is called
CRuntime error
DFunction is ignored
How do you declare a pure virtual function?
Avirtual void func() = 0;
Bvoid func() = 0;
Cvirtual void func();
Dvoid func() override;
What kind of class contains at least one pure virtual function?
AStatic class
BConcrete class
CAbstract class
DFinal class
Explain how virtual functions enable polymorphism in C++.
Think about how the program chooses which function to run when using a base class pointer.
You got /4 concepts.
    Describe the difference between a virtual function and a pure virtual function.
    Consider what happens if you want to force derived classes to implement a function.
    You got /4 concepts.