2017年3月1日 星期三

[C++] Virtual function

If B inherits from A, and redefines a method defined in A, then new instances of B will call
B's version. However, if the method is not virtual, then there is no polymorphic behavior, so if 
an instance of B is referenced as an A, then the method will be A's. For example:
struct A {
    void foo () { std::cout << "A::foo" << std::endl; }
};

struct B : public A {
    void foo () { std::cout << "B::foo" << std::endl; }
};

B b;
b.foo();
A *a = &b;
a->foo();
The output of the code above would be:
B::foo
A::foo
However, if the foo method had been virtual, then B::foo would have been printed twice.

http://stackoverflow.com/questions/11269501/can-i-use-a-method-overriding-a-non-virtual-method

沒有留言:

張貼留言