redefine a non-virtual function in C++

sky*_*oor 11 c++

When I read Effective C++, it says, never redefine a non-virtual function in C++.

However, when I tested it, the code below compiles correctly. So what's the point? It's a mistake or just a bad practice?

class A {

    public:
    void f() { cout<<"a.f()"<<endl;};   
};

class B: public A {
    public:
    void f() { cout<<"b.f()"<<endl;};   
};


int main(){

    B *b = new B();
    b->f(); 
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

bma*_*ies 25

只要您不依赖于虚拟调度行为,重新定义非虚函数就可以了.

本书的作者担心,当结果是对基本方法的调用而不是派生方法时,您将把你B*的函数传递给一个A*然后感到沮丧的函数.

  • 可爱的答案!简而言之,并展示了情感编程的方式. (2认同)

Kor*_*icz 7

Try this:

int main(){
    A *b = new B();
    b->f(); 
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

I think the answer will be obvious once you see the result ;-).

Without being virtual, the late-binding mechanism will not be used, hence the function that is defined for that pointer type will be used, not late-binded function that you want to call. This leads to tons of badly trackable bugs.

Hence, what you are doing is creating a new function. It may be what you intended, but someone reading your code afterwards might expect the above code to work with late-binding. Very confusing.

我真正希望看到的一个功能是在这种情况下发出警告,使用"重新定义"关键字来防止它,但梦想是梦想,而现实就是现实-_-