C++: rationale behind hiding rule

前端 未结 5 1003
旧时难觅i
旧时难觅i 2020-11-27 20:15

What\'s the rationale behind the hiding rule in C++?

class A { void f(int); }
class B : public A { void f(double); } // B::f(int) is hidden
5条回答
  •  心在旅途
    2020-11-27 20:45

    Probably, the reason is template specialization. I give you an example:

    template  struct A { void f() };
    
    template <> struct A<1> { void f(int) };
    
    template 
    struct B: A
    {
      void g() { this->f(); }
    };
    

    The template class B has a method f(), but until you don't create an instance of the class B you don't know the signature. So the call this->f() is anytime "legal". Both GCC and CLang don't report error until you create the instance. But when you call the method g() on a B<1> instance they indicate the error. So the hiding rule keep simpler to check if your code is valid.

    I report the last part of code used in my example.

    int main (int argc, char const *argv[])
    {
      B<0> b0; /* valid */
      B<1> b1; /* valid */
    
      b0.g(); /* valid */
      b1.g(); /* error: no matching function for call to ‘B<1>::f()’ */
    
      return 0;
    }
    

提交回复
热议问题