<<< const cast away: const_cast     Index     Inheritance advice >>>

38. Mistakes and pain caused by careless overriding of virtual and non-virtual functions

  • 
    #include <iostream>
    
    class Base {
    public:
        virtual void vf() const
        {
            std::cout << "Base::vf\n";
        }
    
        void f() const
        {
            std::cout << "Base::f\n";
        }
    };//class Base
    
    class Derived : public Base {
    public:
        // Attempt to "override" virtual:
        virtual void vf()
        {
            std::cout << "Derived::vf\n";
        }
    
        // Override non-virtual:
        void f() const
        {
            std::cout << "Derived::f\n";
        }
    };//class Derived
    
    
  • Functions in derived classes override virtual functions in base classes only if their type is the same .

  • Redefinition of non-virtual functions may also cause confusion,
    especially in a mix-in of virtual and non-virtual functions in one interface.

    
    int main()
    {
        Derived d;
        Derived* dp = &d;
    
        Base* bp = &d;
        dp->vf(); // expected Derived::vf
        dp->f();  // expected Derived::f
        bp->vf(); // expected Derived::vf (it's virtual!)
        bp->f();  // expected Derived::f (confusing for virtual)
        return 0;
    }
    /*Program output:
    Derived::vf
    Derived::f
    Base::vf
    Base::f
    */
    
    
<<< const cast away: const_cast     Index     Inheritance advice >>>