tags:

views:

167

answers:

6

I saw code in a derived class recently in which the programmer put virtual in front of the functions overridden. Is this common? I thought it was very odd and it kind of caught me off guard.

Edit: I'm not asking what virtual does, I'm asking why someone would put virtual in a derived class that is already overriding virtual functions in its base class.

EX:

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

class D : public B {
 public:
  virtual void foo(); // could have just put void foo();
  ...
};
+11  A: 

virtual is needed for overrideable functions at the highest (least derived) level. It is optional, but harmless at lower (more derived) levels. It's good for self-documenting the code.

James Curran
Exactly. The compiler already knows, but other people reading your code might have to track back through multiple header files to find out.
Scott Smith
+2  A: 

I'll assume that you know the purpose of the virtual keyword but wondering why it suddenly appears in a subtype. If I am mistaken, my answer probably won't make much sense but any C++ reference will do.

It is perfectly legal to put virtual in a derived class. As a result, if you have a reference or pointer to that class or any of its subclasses, invocations of this function would be bound dynamically based on the runtime type.

While legal, however, it is not considered good design to have a nonvirtual method in the base class and virtual in an overridden version.

One reason is that you could have an instance of the derived class, and then one pointer to base and one pointer to the derived, and have both pointers aiming at this instance. Invoking the same function on each pointer would then have a different result, since invoking on the pointer declared with the base class would target the definition in the base class.

Uri
+3  A: 

I don't see anything odd in it. In many cases (if not most of the time) programmers create the declaration of the overriding function in the derived class by copy-pasting it from the base class. There's no point in spending the additional effort to manually remove the redundant virtual specifier. Moreover, the explicit virtual makes it easier to see which functions are virtual.

AndreyT
+3  A: 

It is very common. Many style guides recommend it, e.g. Google. The purpose is to enhance readability of the code.

Ralph
A: 

This will help if future derivations also. If someone wants to derive class D and have virtual functions, then its easy to understand

Pardeep
A: 

Another way to enhance readability is to use something like this:

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

class D : public B {
 public:
  /*override*/ void foo();
  ...
};
Sergey Teplyakov