How to override virtual function in good style? [C++]
Asked Answered
H

3

8

guys I know this question is very basic but I've met in few publications (websites, books) different style of override virtual function. What I mean is: if I have base class:

class Base
{
public:
virtual void f() = 0;
};

in some publications I saw that to override this some authors would just say:

void f();     

and some would still repeat the virtual keyword before void. Which form of overwriting is in good style? Thank you for your answers.

Hardfeatured answered 14/3, 2010 at 19:3 Comment(1)
@James McNellis - Thanks, for some strange reason (and the reason is that in Poland we call it overwriting (God why do we have to try to be always that bit more clever in Poland)) I was convinced that the correct way to call this mechanism. Thanks again.Hardfeatured
F
14

This is purely a matter of taste. Some weak arguments can be made back and forth as to the self-documentation value of some styles versus the non-redundancy of others.

Forlini answered 14/3, 2010 at 19:4 Comment(1)
Nice to see the first answer is the best one. Note also the new standard adds some decorators to doc and check just why you are overloading,overriding,hiding,etcPropagandism
D
3

It is not necessary to add the virtual keyword to a method you override in a subclass as this qualifier can not be removed by omitting it in subclass declarations.

It is however good practise to repeat the virtual keyword as it documents which derived functions are virtual in the base class.

This is also recommended by the 'High Integrity C++ Coding Standard Manual'.

which is linked in the C++ FAQ.

Dispenser answered 15/3, 2010 at 1:53 Comment(0)
L
0

I personally use both styles: virtual means that the method can be overridden.

So we have two cases:

  • if you wish the user of your class to know that the method may be overridden, use the virtual keyword
  • if you would prefer to hide this fact (because you provide new methods for example following the Template Pattern), then do not use the virtual keyword

I guess it's yet another way of (ab?)using the keyword.

Landlady answered 15/3, 2010 at 9:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.