Call derived class non virtual member functions from base class pointer

后端 未结 2 1778
失恋的感觉
失恋的感觉 2021-01-16 03:41

We know that, derived class members functions can be accessed through a base class pointer in C++ , provided that these member functions have to be virtual.

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-16 04:10

    I want to call derived class member functions which are present only in derived class & not in base class through base class pointer. How would I achieve this ?

    You cannot call a non-virtual member function of the derived class with a pointer to the base class.

    You'll need a pointer to the derived class. The simplest method is to use dynamic_cast to get a pointer to the derived class, check whether the cast was successful, then call the derived class member function using a derived class pointer.

    A better method would be to provide a virtual member function in the base class and implement it in the derived class.

提交回复
热议问题