0

Do virtual methods bind statically when objects are not created dynamically?

If virtual methods have the best of both worlds (static and dynamic binding when needed), what is the point of having non-virtual methods? In what cases would one prefer their use over virtual ones?

For better explanations I included a simple class hierarchy.

Base Class:

Class Base
{
/*
 Member data, constructors and destructors
*/
public:
  void my_redefined_func();
  virtual void my_overriden_func();
};

Derived Class:

Derived : public Base
{
/*
 Member data, constructors and destructors
*/
public:
  void my_redefined_func();
  virtual void my_overriden_func() override;
};
Michel H
  • 317
  • 3
  • 10
  • virtual _functions_ (C++ doesn't have "methods") often carry a runtime overhead. They are not always as efficient as non-virtual functions. – Drew Dormann Mar 26 '21 at 18:46
  • @DrewDormann They don't though with static dispatching, the vtable addition might be memory overhead though. – Hatted Rooster Mar 26 '21 at 18:47
  • `Base* b = new Derived(); b->my_redefined_func();` will call the Base member function, not the Derived member function. Sometimes that is what is wanted. Other times, it is a problem. – Eljay Mar 26 '21 at 18:48
  • Is this overhead present when there's no dynamic data allocation (related to the first question)? Are the viertual functions statically bound in this case? – Michel H Mar 26 '21 at 18:49
  • 1
    A compiler's optimizer can use the *as if* rule to statically bind the virtual member function. The compiler is not required to do so. The compiler is required to do dynamic dispatch, but the *as if* rule gives it the leeway to optimize the call where possible. – Eljay Mar 26 '21 at 18:51
  • Creating the object dynamically doesn't matter. `Derived d; Base* b = &d;` does the same thing, and raises the same issues. The only difference is that `d` will be destroyed when it goes out of scope, so `delete b;` would be wrong. – Pete Becker Mar 26 '21 at 20:36

0 Answers0