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?
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.
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;
}
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.
To quote the C++ Standard (10.3.2):
If a virtual member function
vfis declared in a classBaseand in a classDerived, derived directly or indirectly fromBase, a member functionvfwith the same name and same parameter list asBase::vfis declared, thenDerived::vfis also virtual (whether or not it is so declared) and it overridesBase::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.
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.