views:

251

answers:

5

Why does the derived class have to declare its methods as virtual for dynamic binding to work even though the methods of the base class are declared virtual?

+4  A: 

It doesn't have to. If a method is declared virtual in a base class, overriding it in a derived class makes the overriding function virtual as well, even if the virtual keyword is not used.

laalto
Thank you, I didn't know that.
Hayato
+2  A: 

Is it? The following code produces the expected output B::f1() (compiled using 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;
}
Naveen
Thank you for your answer, helped a lot.
Hayato
+3  A: 

It doesn't.

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

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

in this code foo() is still virtual in the Derived class even though it isn't declared as such.

shoosh
+2  A: 

To quote the C++ Standard (10.3.2):

If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name and same parameter list as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf.

You can sum up this with: "once virtual, always virtual". However, you can still add the virtual modifier to the overriding member functions in order to make it clear for the user that the class is polymorphic.

Luc Touraille
A: 

One need not to. But i prefer using virtual in the derived class functions too as it will make the dynamic binding associated with those function more clear while reading the code.

nurxb01