What is the output of this C++ program?
#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* obj = new Derived(); obj->show(); delete obj; return 0; }
Think about which version of show() is called when using a base class pointer to a derived object.
The method show() is declared virtual in the base class. This means the derived class's overridden version is called at runtime, even when accessed through a base class pointer.
What will this program print?
#include <iostream> using namespace std; class Base { public: void display() { cout << "Base display" << endl; } }; class Derived : public Base { public: void display() { cout << "Derived display" << endl; } }; int main() { Base* ptr = new Derived(); ptr->display(); delete ptr; return 0; }
Check if the base class method is declared virtual or not.
Since display() is not virtual in the base class, the base class version is called even when the pointer points to a derived object.
What error does this code produce?
#include <iostream> using namespace std; class Parent { public: virtual void func(int x) { cout << "Parent func: " << x << endl; } }; class Child : public Parent { public: void func(double x) override { cout << "Child func: " << x << endl; } }; int main() { Child c; c.func(5); return 0; }
Check the parameter types in the overridden method and the use of override keyword.
The func method in Child has a different parameter type (double) than the base class (int). Using override keyword causes a compilation error because it does not actually override any base method.
Why is it important to declare a destructor as virtual in a base class when using method overriding?
Think about what happens when deleting an object through a base class pointer.
If the base class destructor is not virtual, deleting a derived object through a base pointer calls only the base destructor, causing resource leaks. Declaring it virtual ensures the derived destructor runs properly.
What is the output of this program?
#include <iostream> using namespace std; class A { public: virtual void f(int x) { cout << "A::f(int): " << x << endl; } virtual void f(double x) { cout << "A::f(double): " << x << endl; } }; class B : public A { public: void f(int x) override { cout << "B::f(int): " << x << endl; } void f(float x) { cout << "B::f(float): " << x << endl; } }; int main() { B b; A* ptr = &b; ptr->f(10); // call 1 ptr->f(10.5); // call 2 b.f(10.5f); // call 3 return 0; }
Remember which methods are virtual and which are overridden. Also consider implicit conversions and overload resolution.
Call 1: ptr->f(10) calls B::f(int) because it overrides A::f(int).
Call 2: ptr->f(10.5) calls A::f(double) because B does not override f(double).
Call 3: b.f(10.5f) calls B::f(float) because b is an object of B and f(float) is a better match than f(double).