Dynamic binding in C ++

Why should a derived class declare its methods virtual for dynamic binding to work, even if the methods of the base class are declared virtual?

+3
source share
5 answers

It's not obligatory. If a method is declared virtual in the base class, overriding it in the derived class also makes the overriding function virtual, even if the keyword is virtualnot used.

+5
source

This is not true.

class Base
{
    virtual void foo() {}
};

class Derived : public Base
{
    void foo() {}
}

in this code foo(), it remains virtual in the class Derived, even if it is not declared as such.

+3
source

? B:: f1() ( VS2008):

class A
{
public:

    virtual ~A(){}
      virtual void f1()
      {
        std::cout<<"A::f1()\n";
      }

        virtual void f2()
      {
        std::cout<<"A::f2()\n";
      }
};

class B : public A
{
public:
       void f1()
      {
        std::cout<<"B::f1()\n";
      }

         void f2()
      {
        std::cout<<"B::f2()\n";
      }
};


int  main()
{
    B b;
    A* p = &b;
    p->f1();

    return 0;
}
+2

++ (10.3.2):

- vf ​​ Base Derived, Base, - vf Base::vf, Derived::vf ( , ), Base::vf.

: " , ". , virtual -, , .

+2

Not necessary. But I prefer to use the virtual functions of the derived class, as this will make the dynamic binding associated with these functions more understandable when reading the code.

0
source

Source: https://habr.com/ru/post/1711053/


All Articles