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
Зареєструйся Зараз
або Підпишись на майбутні тести