What will the following code display?
#include <iostream>

struct A
{
    virtual void method() const { std::cout << "A" << std::endl; }
    virtual ~A(){}
};

struct B : A
{
    virtual void method() { std::cout << "B" << std::endl; }
};

int main() {
    A * ptr = new B(); 
    ptr->method();
    delete ptr;
    return 0;
}
Explanation
It's a typical mistake of a novice in overloading. A function signature includes the const and volatile qualifications, so we overload nothing in the structure B and declare the new virtual function. There is a useful keyword override in C++11, which allows controlling such things.
Also ​"virtual void method() override" in B won't compile, because it overloads nothing.

Следи за CodeGalaxy

Мобильное приложение Beta

Get it on Google Play
Обратная Связь
Cosmo
Зарегистрируйся сейчас
или Подпишись на будущие тесты