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

后端 未结 3 1200
时光说笑
时光说笑 2021-01-27 14:19

In the following code

#include 
using namespace std;

class A {
  public:
    A() {}
    virtual ~A() {};
};

class B : public A {
  public:
             


        
3条回答
  •  孤独总比滥情好
    2021-01-27 14:48

    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.

提交回复
热议问题