Deepen your understanding of virtual functions and dynamic dispatch in object-oriented programming. This quiz covers core principles, use cases, and common pitfalls to help you reinforce key concepts related to polymorphism and runtime method resolution.
Which statement best describes the primary purpose of a virtual function in object-oriented programming?
Explanation: Virtual functions allow derived classes to provide specific implementations of functions defined in a base class, supporting polymorphism and dynamic dispatch at runtime. Compilation speed is unrelated to virtual functions; if anything, virtual functions slightly decrease compile-time optimization due to runtime resolution. Restricting access is handled by access specifiers, not virtual functions. Data member initialization is managed by constructors, not virtual methods.
Given a base pointer pointing to a derived object, what happens if a non-virtual member function is called through the base pointer?
Explanation: When calling a non-virtual function through a base pointer, the function call is resolved at compile time, so the base class version is executed regardless of the actual object type. Only virtual functions support dynamic dispatch and allow the derived implementation to be used. There is no ambiguity or runtime error, and the call is not ignored by the compiler.
Why is it important to declare a base class destructor as virtual when using polymorphism, especially with dynamic memory allocation?
Explanation: A virtual base class destructor guarantees that when a derived object is deleted via a base pointer, the correct derived class destructor gets called, ensuring proper cleanup. Not marking the destructor virtual can lead to resource leaks if only the base class destructor is executed. Constructors are not affected by the virtual keyword, and making a destructor virtual does not make a class abstract. Virtual destructors may slightly slow down, not speed up, deletion due to dynamic lookup.
What is the effect of declaring a pure virtual function in a class using '= 0'?
Explanation: Declaring a pure virtual function makes the class abstract, which means you cannot create objects of that class type directly. The function remains a member of the base class and must be overridden by derived classes, but it's not removed. Not all members are required to be virtual, and pure virtual status does not make it a friend function.
Which role does the vtable play in supporting dynamic dispatch for virtual functions?
Explanation: The vtable is a mechanism that allows the program to select the correct function implementation at runtime when a virtual call occurs, enabling dynamic dispatch. It does not store actual data member values, as those are part of the object instance. The vtable is critical at runtime, not just compile-time. Access permissions are defined using keywords, not by the vtable.