Skip to content
Related Articles

Related Articles

Improve Article

C++ | Virtual Functions | Question 2

  • Difficulty Level : Medium
  • Last Updated : 28 Jun, 2021
Geek Week

Predict output of the following program




#include<iostream>
using namespace std;
  
class Base
{
public:
    virtual void show() { cout<<" In Base \n"; }
};
  
class Derived: public Base
{
public:
    void show() { cout<<"In Derived \n"; }
};
  
int main(void)
{
    Base *bp = new Derived;
    bp->show();
  
    Base &br = *bp;
    br.show();
  
    return 0;
}

(A)

In Base 
In Base 

(B)

In Base 
In Derived

(C)

In Derived
In Derived

(D)

In Derived
In Base 


Answer: (C)

Explanation: Since show() is virtual in base class, it is called according to the type of object being referred or pointed, rather than the type of pointer or reference.

Quiz of this Question

Take a step-up from those “Hello World” programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.
My Personal Notes arrow_drop_up
Recommended Articles
Page :