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

后端 未结 3 1236
时光说笑
时光说笑 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:59

    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&).

提交回复
热议问题