Why is not overloaded function for derived class object invoked when given a pointer to base class in C++?

不羁岁月 提交于 2019-12-02 11:42:37

The static type of expression *a is A because a was declared as

A* a = new B;

The compiler resolves the selection of overloaded functions using the static type of the argument.

Even when virtual functions are called the compiler uses the static type of the object to call appropriate function. The difference is only that the compiler uses the table of pointers to virtual functions to indirectly call the required function.

You need to make process() a virtual member function of A, B:

class A {
  public:
    A() {}
    virtual ~A() {};
    virtual void process() const { cout << "processing A" << endl; }
};

class B : public A {
  public:
    B() {}
    virtual ~B() {};
    virtual void process() const override { cout << "processing B" << endl; }
};

int main(void) {
    A* a = new B;
    a->process();
    return 0;
}

In your current code, *a is of type A&, so the closest match to process(*a); is the first overload (for const A&).

void process(const A&); is a better (exact) match, since dereferencing A* gives you A&.

Short answer, but there isn't much more to say unless you want a reference from the standard.

You could dynamic_cast the result of *a and that would give you a B&, but that's smelly desing. What you probably want is a virtual function in A that's overriden in B (assume it's called foo). Then, calling a->foo() would dispatch to B::foo.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!