Recall & Review
beginner
What is a base class pointer in C++?A base class pointer is a pointer that points to an object of the base class or any of its derived classes. It allows accessing base class members and supports polymorphism when used with virtual functions.Click to reveal answer
beginner
How does a base class pointer behave when pointing to a derived class object?A base class pointer can point to a derived class object, but it can only access members defined in the base class unless virtual functions are used to enable polymorphic behavior.Click to reveal answer
intermediate
Why do we use virtual functions with base class pointers?Virtual functions allow a base class pointer to call the derived class's overridden function at runtime, enabling dynamic dispatch and polymorphism.Click to reveal answer
intermediate
What happens if a base class pointer calls a non-virtual function overridden in a derived class?The base class version of the function is called, not the derived class version, because non-virtual functions are resolved at compile time based on the pointer type.Click to reveal answer
beginner
Show a simple example of a base class pointer pointing to a derived class object and calling a virtual function.#include <iostream>
using namespace std;
class Base {
public:
virtual void show() { cout << "Base show" << endl; }
};
class Derived : public Base {
public:
void show() override { cout << "Derived show" << endl; }
};
int main() {
Base* ptr = new Derived();
ptr->show(); // Output: Derived show
delete ptr;
return 0;
}Click to reveal answer
What does a base class pointer point to in C++?
✗ Incorrect
A base class pointer can point to objects of the base class or any class derived from it.
Which keyword enables a base class pointer to call the derived class's overridden function?
✗ Incorrect
The 'virtual' keyword allows dynamic dispatch so the derived class's function is called.
If a base class pointer calls a non-virtual function overridden in a derived class, which function is executed?
✗ Incorrect
Non-virtual functions are resolved at compile time based on pointer type, so base class function runs.
What is the output of this code snippet?
class Base { public: virtual void f() { cout << "Base"; } };
class Derived : public Base { public: void f() override { cout << "Derived"; } };
Base* p = new Derived();
p->f();
✗ Incorrect
Because f() is virtual, the derived class version is called at runtime.
Can a base class pointer access members unique to the derived class?
✗ Incorrect
To access derived-only members, the pointer must be cast to the derived class type.
Explain how base class pointers support polymorphism in C++.
Think about how the pointer calls functions depending on the actual object type.
You got /5 concepts.
Describe what happens when a base class pointer calls a non-virtual function overridden in a derived class.
Consider how the compiler decides which function to call.
You got /4 concepts.