Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to specify virtual on the sub-classes methods as well?

This has probably been asked before on SO, but I was unable to find a similar question.

Consider the following class hierarchy:

class BritneySpears {   public:      virtual ~BritneySpears(); };  class Daughter1 : public BritneySpears {   public:      virtual ~Daughter1(); // Virtual specifier };  class Daughter2 : public BritneySpears {   public:      ~Daughter2(); // No virtual specifier }; 

Is there a difference between Daughter1 and Daughter2 classes ?

What are the consequences of specifying/not specifying virtual on a sub-class destructor/method ?

like image 652
ereOn Avatar asked Jul 02 '10 15:07

ereOn


People also ask

Is it mandatory to define virtual function?

It is not mandatory for the derived class to override (or re-define the virtual function), in that case, the base class version of the function is used.

Do I have to implement all virtual methods?

Derived classes do not have to implement all virtual functions themselves. They only need to implement the pure ones. That means the Derived class in the question is correct.

Is there any reason to mark a function virtual If you are not going to have a derived class?

No, the virtual keyword on derived classes' virtual function overrides is not required.

Is virtual keyword needed in derived class?

The virtual keyword can be used when declaring overriding functions in a derived class, but it is unnecessary; overrides of virtual functions are always virtual. Virtual functions in a base class must be defined unless they are declared using the pure-specifier.


1 Answers

No you technically do not need to specify virtual. If the base method is virtual then C++ will automatically make the matching override method virtual.

However you should be marking them virtual. The method is virtual after all and it makes your code much clearer and easier to follow by other developers.

like image 50
JaredPar Avatar answered Oct 02 '22 19:10

JaredPar