Virtual inheritance and static inheritance - mixing in C++

前端 未结 6 666
误落风尘
误落风尘 2020-12-29 13:33

If you have something like this:

#include 

template class A
{
public:
    void func()
    {
        T::func();
    }
};

c         


        
6条回答
  •  执笔经年
    2020-12-29 14:22

    Whether the function is dynamically dispatched or not depends on two things:

    a) whether the object expression is a reference or pointer type

    b) whether the function (to which overload resolution resolves to) is virtual or not.

    Coming to your code now:

      C c; 
      c.func();   // object expression is not of pointer/reference type. 
                  // So static binding
    
      A  & ref = c; 
      ref.func(); // object expression is of reference type, but func is 
                  // not virtual. So static binding
    
    
      A* ptr = new D; 
      ptr->func(); // object expression is of pointer type, but func is not 
                   // virtual. So static binding 
    

    So in short, 'func' is not dynamically dispatched.

    Note that :: suppresses virtual function call mechanism.

    $10.3/12- "Explicit qualification with the scope operator (5.1) suppresses the virtual "call mechanism.

    The code in OP2 gives error because the syntax X::Y can be used to invoke 'Y' in the scope of 'X' only if 'Y' is a static member in the scope of 'X'.

提交回复
热议问题