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++?
✗ Incorrect
The keyword
virtual is used to declare virtual functions in C++.If a base class function is virtual, which function is called when using a base class pointer to a derived object?
✗ Incorrect
With virtual functions, the derived class function is called at runtime, enabling polymorphism.
What happens if you call a non-virtual function through a base class pointer to a derived object?
✗ Incorrect
Non-virtual functions use static binding, so the base class function is called.
How do you declare a pure virtual function?
✗ Incorrect
A pure virtual function is declared by assigning 0 after the declaration.
What kind of class contains at least one pure virtual function?
✗ Incorrect
A class with at least one pure virtual function is called an abstract 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.