5

Does the virtual qualifier to a virtual function of base class, in the derived class makes any difference ?

class b
{
   public:
   virtual void foo(){}
};

class d : public b
{
  public:
  void foo(){ .... }
};

or

class d : public b
{
  public:
  virtual void foo(){ .... }
}; 

Is there any difference in these two declarations, apart from that it makes child of d make aware of virtuality of foo() ?

Mat
  • 202,337
  • 40
  • 393
  • 406
amneet
  • 115
  • 1
  • 5
  • afaik, it makes a difference if something else derives from class d โ€“ K Mehta Aug 17 '11 at 19:05
  • @Kshitij: No, even then it doesn't make any difference. Once `foo` is virtual, its virtual forever, no matter how far you go from the base in the class-hierarchy. โ€“ Nawaz Aug 17 '11 at 19:12

4 Answers4

6

It makes no difference. foo is virtual in all classes that derive from b (and their descendants).

From C++03 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.

Mat
  • 202,337
  • 40
  • 393
  • 406
2

No difference - it's a virtual override either way.

It's a matter of style and has been definitively discussed here

Community
  • 1
  • 1
StuartLC
  • 104,537
  • 17
  • 209
  • 285
1

It's better style to include the virtual keyword. But it's not required.

1

No difference.

Once foo is virtual, its virtual forever in the class-hierarchy, no matter how far you go from the base in the class-hierarchy.

But I prefer to write virtual even in overrridden functions, because it adds readability to the code, which matters a lot.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • For extra safety C++11 adds some override keyword which you can specify, so the compiler checks for you that when overriding a virtual function, you did not make a mistake in the signature and overloaded it accidentally โ€“ PlasmaHH Aug 17 '11 at 19:13