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

后端 未结 3 1198
时光说笑
时光说笑 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 15:06

    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.

提交回复
热议问题