0

The general good practice is that trivial constructors, destructors, get/set functions, etc, can be directly defined inside a class definition in a header file, rather than providing their bodies in a cpp file. That makes them all implicitly inline.

But what if I need to make that trivial destructor virtual (anticipating that my class will be sub-classed in future)? Then my destructor becomes inline as well as virtual. But "inline" and "virtual" do not seem to go together, since virtual is resolved at run-time whereas "inline" is about directly pasting the code in the caller's code during compilation!

Please help me understand how a destructor becomes both virtual and inline at the same time!

softwarelover
  • 1,009
  • 1
  • 10
  • 22
  • _That makes them all implicitly inline_ Actually no. It makes them _candidates_ for inlining. And with modern linkers, functions defined in different translation units become candidates for inlining as well, if you build with the appropriate flags. – Paul Sanders Jul 02 '20 at 16:36
  • 2
    `inline` does not mean inline the code: https://en.cppreference.com/w/cpp/language/inline – NathanOliver Jul 02 '20 at 16:37
  • 3
    Does this answer your question? [Are inline virtual functions really a non-sense?](https://stackoverflow.com/questions/733737/are-inline-virtual-functions-really-a-non-sense) – yaodav Jul 02 '20 at 16:37
  • 3
    The C++ `inline` keyword has **nothing** to do with inlining _calls_ to a function. All it does is allow a function to be defined in multiple translation units (as long as all of the definitions are the same). That is, it allows a function to be defined inline in a header. This may assist the compiler in _being able to_ inline calls to the function since it's definition is visible in more places, but the compiler will make that decision on its own. – Miles Budnek Jul 02 '20 at 16:39
  • Thanks, all. As Nathan said, "candidates for inlining" seems appropriate. @yaodav, I think that link answers my question in this phrase: "The only time an inline virtual call can be inlined is when the compiler knows the "exact class" of the object which is the target of the virtual function call. This can happen only when the compiler has an actual object rather than a pointer or reference to an object. I.e., either with a local object, a global/static object, or a fully contained object inside a composite." – softwarelover Jul 02 '20 at 16:49
  • @Miles, yes you summed it up all.. Thanks. – softwarelover Jul 02 '20 at 17:17

0 Answers0