What will be the output of the following C++ code? [code] #include <iostream> #include <exception> using namespace std;

thanhthao

New member
What will be the output of the following C++ code?
Code:
    #include <iostream>
    #include <exception>
    using namespace std;
    class base { virtual void dummy() {} };
    class derived: public base { int a; };
    int main () 
    {
        try 
        {
            base * pba = new derived;
            base * pbb = new base;
            derived * pd;
            pd = dynamic_cast<derived*>(pba);
            if (pd == 0) 
                cout << "Null pointer on first type-cast" << endl;
            pd = dynamic_cast<derived*>(pbb);
            if (pd == 0) 
                cout << "Null pointer on second type-cast" << endl;
        } 
        catch (exception&#038; e) 
        {
            cout << "Exception: " << e.what();
        }
        return 0;
    }
A. Null pointer on first type-cast
B. Null pointer on second type-cast
C. Exception
D. Null pointer on third type-cast
 
Answer: b
Explanation: In this program, We apply the dynamic cast to pd. Based on the value in the pd, it produces the output.
Output:
Code:
$ g++ rtti.cpp
$ a.out
Null pointer on second type-cast
 

Tìm kiếm

Back
Top