WBJECA 2025 Computer PYQ — What is the output of the following C++ code #include <iostream> … | Mathem Solvex | Mathem Solvex
Tip:A–D to answerE for explanationV for videoS to reveal answer
WBJECA 2025 — Computer PYQ
WBJECA | Computer | 2025
What is the output of the following C++ code
#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;
Derived d;
ptr = &d;
ptr->show();
return 0;
}
Choose the correct answer:
A.
Compilation error
B.
Base
C.
Derived
(Correct Answer)
D.
Runtime error
Correct Answer:
Derived
Explanation
The code demonstrates runtime polymorphism using virtual functions.
Base Class Pointer: A pointer of the base class (Base* ptr) is used to point to an object of the derived class (Derived d).
Virtual Function: The function show() in the base class is declared as virtual, which enables dynamic binding.
Override: In the derived class, the show() function overrides the base class function.
Dynamic Binding: When ptr->show() is called, the compiler checks the type of the object being pointed to at runtime, rather than the type of the pointer. Since ptr points to an instance of Derived, the Derived version of the function is executed.
Explanation
The code demonstrates runtime polymorphism using virtual functions.
Base Class Pointer: A pointer of the base class (Base* ptr) is used to point to an object of the derived class (Derived d).
Virtual Function: The function show() in the base class is declared as virtual, which enables dynamic binding.
Override: In the derived class, the show() function overrides the base class function.
Dynamic Binding: When ptr->show() is called, the compiler checks the type of the object being pointed to at runtime, rather than the type of the pointer. Since ptr points to an instance of Derived, the Derived version of the function is executed.