• Advertisement
Sign in to follow this  

Virtual Method Question

This topic is 3704 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

If I have a virtual method in a class, do I have to re-declare that method in the derived class like this?:
class Base
{
public:
   virtual void method() {}
};

class Derived : public Base
{
public:
   void method();
};

void Derived::method()
{
}

It seems like that would be silly if I had lots and lots of derived classes and had to update them all each time I added a new method to the base class. I just wanted to make sure that I wasn't doing any needless copying.

Share this post


Link to post
Share on other sites
Advertisement
You should only declare (and define) a method in the derived class if you need it to override the base class behavior. Otherwise, leave it alone.

Share this post


Link to post
Share on other sites
If it's a virtual method with an implementation in the base class, as is the case with the code you posted, then the method will be inherited and optionally overriden if you need to give it a new behaviour.

If the virtual method is 'pure virtual' then it needs to be given an implementation in the derived class before you can create an instance of the derived class.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement