3

Imagine having the following classes:

class A {
    virtual void foo();
};

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

I know that using 'override' prevents broken polymorphism. But is it good style to still add the 'virtual' keyword to the derived method?

MrBolton
  • 47
  • 6
  • Good question, this might help http://stackoverflow.com/questions/2443353/how-to-override-virtual-function-in-good-style-c Largely down to personal choice. I don't repeat. – Bathsheba Oct 12 '16 at 07:46
  • It depends on what do you expect when remove `virtual` keyword from the base class member function. – songyuanyao Oct 12 '16 at 07:51
  • But does having `virtual` in a child class `virtual`-ise the base class where `virtual` is missing? – Bathsheba Oct 12 '16 at 07:51
  • @Bathsheba.. i don't think `virtual`-sation gets propagated upwards. – Saurav Sahu Oct 12 '16 at 07:54
  • 1
    @SauravSahu: That makes two of us: my question was a rhetorical one. – Bathsheba Oct 12 '16 at 07:55
  • I always use virtual, because it makes the prototype of the function look (nearly) the same in all places, with 'override' becoming single extension in children. – Thinkeye Oct 12 '16 at 08:07
  • Related, w.r.t. `override` keyword: [Implementing pure virtual function from abstract base class: does override specifier have any meaning?](http://stackoverflow.com/questions/39370403). – dfrib Oct 12 '16 at 08:10

1 Answers1

2

But is it good style to still add the 'virtual' keyword to the derived method?

In your case, virtual keyword is implicit in derived class methods as it is propagated down implicitly from class A to class B.

Compilers may complain through warning if 'virtual' keyword is not mentioned explicitly.

Pros: Gives clear indication of being virtual, especially useful in deep class hierarchies.

Cons: Not cleaner or clearer look.

Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79
  • 1
    You are ignoring the fact that `override` can only be applied to virtual functions. – juanchopanza Oct 12 '16 at 08:00
  • Yes that is true. Derived class method is anyway implicitly virtual. So we can directly append `override` keyword in its declaration. – Saurav Sahu Oct 12 '16 at 08:12
  • So to keep compilers quit AND prevent broken polymorphism, I think the best choice is to use both keywords simultaniously – MrBolton Oct 12 '16 at 14:21