What will be printed out as a result of the following code execution?
#include <iostream>
class base
{
public:
    base() 
    {
        std::cout << "base()";
    }
    virtual ~base() 
    {
        std::cout << "~base()";
    }
    void f()
    {
        std::cout << "base f()";
    }
};
class derived: public base
{
public:
    derived()
    {
        std::cout << "derived()";
    }
    ~derived()
    {
        std::cout << "~derived()";
    }
    void f()
    {
        std::cout << "derived f()";
    }
};
int main()
{
    base* ob = new derived;
    dynamic_cast<derived*>(ob)->f(); 
    return 0;
}
Explanation
1. A derived object is created on the heap, its constructors print - base()derived()
2. The pointer to derived is cast (downcasting) to the pointer to base and stored in the variable ob.
3. The pointer to base is cast (upcasting) to the pointer to derived and the function f() is called, which prints - derived f().
4. The program terminates, while the deletion of the object is forgotten (memory leak) - destructors are not called, nothing is printed additionally.

Слідкуй за CodeGalaxy

Мобільний додаток Beta

Get it on Google Play
Зворотній Зв’язок
Cosmo
Зареєструйся Зараз
або Підпишись на майбутні тести