首页 > 技术文章 > 笔试中常出现的虚函数问题

longf0720 原文

#include <iostream>
#include <cstdio>

struct A {
    void foo() { printf("foo"); }

    virtual void bar() { printf("bar"); }

    A() { bar(); }
};

struct B : A {
    void foo() { printf("b_foo"); }

    void bar() { printf("b_bar"); }
};

int main() {
    A *p = new B;
    p->foo();
    p->bar();
    B b;
    b.foo();
    return 0;
}

执行结果:
barfoob_barbarb_foo

推荐阅读