开发者

Same function name , one with const at the tail

Given the following code :

#include <iostream>
using namespace std;

class A
{
public:
    virtual void func() {cout << "func A" << endl;}
};

class B : public A
{
public:
    void func() const {cout << "func B" << endl;}
};

int main()
{
    A *pa = new B;
    pa->func();

    B *pb = new 开发者_开发问答B;
    pb->func();
    return 0;
}

output is :

func A  // pa->func();
func B  // pb->func();

Why,when doing pb->func(); the method of B would work and not the other one (that B inherited from A) ?

thanks ,Ronen


The method in B does not override the method in A so the virtual declaration shouldn't (as it doesn't) cause the method in B to be called. Consider:

class foo
{
public:
    void bar();
    void bar() const;
}

These are two different methods, one called for a non-const object and the other for a const object.

In order for your code to work as you want, the method in A must also be declared const.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜