Question:

What is the output of the following code:

#include 

class Base {
    virtual void method() {std::cout << "from Base" << std::endl;}
public:
    virtual ~Base() {method();}
    void baseMethod() {method();}
};

class A : public Base {
    void method() {std::cout << "from A" << std::endl;}
public:
    ~A() {method();}
};

int main(void) {
    Base* base = new A;
    base->baseMethod();
    delete base;
    return 0;
}

Answer:

The above will output:

from A
from A
from Base

The important thing to note here is the order of destruction of classes and how Base’s method reverts back to its own implementation once A has been destroyed.


Keywords:

© 2017 QuizBucket.org