Examveda

What will be the output of the following C++ code?
#include <iostream>
using namespace std;
struct A 
{
    virtual void f()  
    { 
        cout << "Class A" << endl; 
    }
};
struct B : A 
{
    virtual void f() 
    { 
        cout << "Class B" << endl;
    }
};
struct C : A 
{
    virtual void f() 
    {
        cout << "Class C" << endl; 
    }
};
void f(A* arg) 
{
    B* bp = dynamic_cast<B*>(arg);
    C* cp = dynamic_cast<C*>(arg);
    if (bp)
        bp -> f();
    else if (cp)
        cp -> f();
    else
        arg -> f();  
};
int main() 
{
    A aobj;
    C cobj;
    A* ap = &cobj;
    A* ap2 = &aobj;
    f(ap);
    f(ap2);
}

A. Class C

B. Class A

C. Both Class C & A

D. Class D

Answer: Option C


Join The Discussion

Related Questions on C plus plus miscellaneous

What is the difference between '++i' and 'i++' in C++?

A. None of the above

B. They both have the same effect

C. '++i' increments the value of 'i' before returning it, while 'i++' increments the value of 'i' after returning it

D. '++i' increments the value of 'i' after returning it, while 'i++' increments the value of 'i' before returning it