Is there a reason to declare a method virtual without inheritance?

Is there a reason to declare a method virtual

if the class is not subclassed and is always used directly?

For example:

class Foo {
  public:
    virtual void DoBar {
      // Do something here.
    }
}

      

I stumbled upon this in some code I was reading and couldn't find any excuse.

Thank!

+3


source to share


3 answers


Well, the gist of the keyword is virtual

directly related to inheritance. This is an excerpt from CPP Ref : -

Virtual Members A virtual member is a member function that can be overridden in a derived class while retaining its invocation properties through references. The syntax for a function to become virtual is this precedes its declaration with the virtual keyword



So IMHO - the question to your question - no - doesn't make sense - unless the code has changed since the original implementation - and trust me this happens a lot!

+1


source


This is useful when writing library code to accommodate a future programmer who might want to extend the class and provide custom behavior. For example, GUI libraries usually have a virtual function Paint()

or virtual mouse function . They provide standard implementations, but they allow for extensibility.



+1


source


If this class is to be obtained then it makes sense. These decisions must be made when defining the architecture of the program and determining what can be done with the interfaces. If they don't want this to happen, then it shouldn't be virtual. If they want it to be retrieved from now on, it must be virtual (and it must make a virtual destructor as well).

+1


source







All Articles