Derived class object base class pointer address is assigned, means for calling the base class and derived classes

The  derived class object address  assigned to the base class pointer and a derived class pointer , the function of the same name may occur override and hide situation.

override:  Derived function class function base class of the same name, the same parameters, and the base class function comprising virtual key

Hide: functions assigned amphibians shields the function of the base class of the same name rules are as follows:

  1. Derived class base class function and function of the same name, different parameters, regardless of whether there is the virtual keyword, the base class function will be hidden;
  2. Derived class base class function and function of the same name, the same parameters, there is no virtual keyword, the base class function will be hidden.

Above excerpt from the interview programmers book << >>


 

Hide or feel for a derived class pointer for ah, the derived class object address is assigned to the base class pointer, the pointer will still call the base class function is not the override. Pointing to the base part derived class object? 

#include <iostream>
using namespace std;

class base{
public:
    virtual void f(float x) { cout << "Base::f(float) " << x <<  endl; }
    void g(float x) { cout << "Base::g(float) " << x << endl; }
    void h(float x) { cout << "Base::h(float) " << x << endl; }
};

class derived:{
basispublic public:
    virtual void f(float x) { cout << "Derived::f(float) " << x << endl; }
    void g(int x) { cout << "Derived::g(int) " << x << endl; }
    void h(float x) { cout << "Derived::h(float) " << x << endl; }
};

int main()
{
    derived DD;
    base *pb = &DD;
    derived *pd = &DD;
pb
->f(3.14f); pd->f(3.14f); pb->g(2.22f); pd->g(2.22f); pb->g(2); pd->g(2); pb->h(1.21f); pd->h(1.21f); }

The result:  (in writing executed this page)     // add their own space, in order to look good

Derived::f(float) 3.14
Derived::f(float) 3.14

Base::g(float) 2.22 Derived::g(int) 2

Base::g(float) 2 Derived::g(int) 2

Base::h(float) 1.21 Derived::h(float) 1.21

 

 

 

Guess you like

Origin www.cnblogs.com/heifengli/p/10974267.html