Using 'virtual' in derived class
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 o开发者_如何学运维ff 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();
...
};
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.
These answers (and this practice) are outdated. As of C++11, you should use the override
keyword to explicitly specify that a virtual function overrides another virtual function. Your compiler will throw an error if you try to override
something that isn't a virtual function in the base class!
It is very common. Many style guides recommend it, e.g. Google. The purpose is to enhance readability of the code.
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.
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();
...
};
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.
This will help if future derivations also. If someone wants to derive class D and have virtual functions, then its easy to understand
精彩评论