Ambiguity in static polymorphism [duplicate]

本小妞迷上赌 提交于 2019-12-12 00:13:24

问题


Quite a simple question actually but one which is bugging me a lot and I'm unable to find a sound answer for it.

How is the function call d.show(); NOT ambiguous for the following code AND why does b->show(); after b = &d; leads to the calling of Base_::show()?

#include <iostream>

using std::cout;

class Base_
{

     public:
          void show()
          {
               cout<<"\nBase Show";
          }
};

class Derived_ : public Base_
{
     public:
          void show()
          {    
              cout<<"Derived Show"<<endl;
          }     
};

int main()
{
     Base_ b;
     Derived_ d;
     b->show(); 
     d.show();
}

回答1:


This is called "Name Hiding" in C++. Essentially, if a class defines a function, it hides all functions with the same name from parent classes. Also worth noting, if you had a Base_* to a derived object, and called that function, it would call the base classes version as it is not virtual and will not attempt to find overrided implementations in derived classes.



来源:https://stackoverflow.com/questions/32655484/ambiguity-in-static-polymorphism

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!