Why should I use the “using” keyword to access my base class method?

后端 未结 4 1904
无人共我
无人共我 2020-11-27 11:19

I wrote the below code in order to explain my issue. If I comment the line 11 (with the keyword \"using\"), the compiler does not compile the file and displays this error: <

相关标签:
4条回答
  • 2020-11-27 11:49

    Surprisingly this is standard behavior. If a derived class declares a method with the same name as a method defined by the base class, the derived class' method hides the base class' one.

    See C++ FAQ

    0 讨论(0)
  • 2020-11-27 12:04

    If in a derived class any over loaded function is redefined then all the overloaded function in the base class is hidden. One way to include both the functionality is to avoid function overloading in classes. or You can use using keyword, as used.

    0 讨论(0)
  • 2020-11-27 12:07

    The action declared in the derived class hides the action declared in the base class. If you use action on a Son object the compiler will search in the methods declared in Son, find one called action, and use that. It won't go on to search in the base class's methods, since it already found a matching name.

    Then that method doesn't match the parameters of the call and you get an error.

    See also the C++ FAQ for more explanations on this topic.

    0 讨论(0)
  • 2020-11-27 12:07

    A note of caution: The need to use a "using" in this situation is a red flag that your code may be confusing for other developers (after all it confused the compiler!). It is likely that you should rename one of the two methods to make the distinction clear to other programmers.

    One possibility:

    void action( const char how )
    { 
      takeAction( &how ); 
    }
    void action( const char * how )
    {
      takeAction(how);
    }
    virtual void takeAction(const char * how) = 0;
    
    0 讨论(0)
提交回复
热议问题