Virtual functions in derived class

Started by
1 comment, last by JakeM 17 years, 4 months ago
Forgive my ignorance, but is there any difference between Derived classes 1 & 2? Since MyFunction() is already defined as a virtual function in the base class, is it necessary to use the virtual keyword in the derived class? Or is the only reason to use the virtual keyword in the derived class is to make it more apparent to the programmer that MyFunction() is indeed a virtual function? Used for the sake of clarity?

class Base {
public:
   virtual void MyFunction();
};

class Derived1 : public Base {
public:
   void MyFunction();
};

class Derived2 : public Base {
public:
   virtual void MyFunction(); 
};
Advertisement
There's no difference between them. While you are not required to use the virtual keyword in derived classes, I usually prefer to do so.

For example, say Base is declared in file Base.h and Derived1 is in Derived.h - if I was to later create a class that derives from Derived1 you can tell that the function MyFunction() is virtual by looking in the file Derived.h. If it's not marked as virtual there it's not immediately obvious that it is a virtual function.
Thanks!
It's been awhile since I've used virtual functions, and I couldn't find a concrete answer after searching for it.

This topic is closed to new replies.

Advertisement