Sign in to follow this  

Virtual functions in derived class

This topic is 4043 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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(); 
};

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 4043 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this