Are Inline Virtual Functions Really a Myth?
In a code review, the comment "virtual functions need not be inline" raises questions about the use of inline virtual functions. Despite their potential benefits, doubts arise about their practicality.
In scenarios where functions are called directly on objects, inline virtual functions may seem suitable. However, one may wonder why virtual functions would be used if objects are used for method calls.
The code snippet below exemplifies the issue:
class Temp { public: virtual ~Temp() {} virtual void myVirtualFunction() const { cout << "Temp::myVirtualFunction" << endl; } }; class TempDerived : public Temp { public: void myVirtualFunction() const { cout << "TempDerived::myVirtualFunction" << endl; } }; int main() { TempDerived aDerivedObj; // Compiler expands virtual functions aDerivedObj.myVirtualFunction(); // Object type for Temp* is known Temp* pTemp = &aDerivedObj; pTemp->myVirtualFunction(); return 0; }
While the compiler can inline the virtual function call when the exact class of the object is known (e.g., aDerivedObj), it cannot do so when the object is accessed through a pointer (pTemp).
This limitation raises the question: should inline virtual functions be avoided since their expansion is often restricted?
The Answer:
Virtual functions can be inlined in certain circumstances, as described in the C FAQ:
"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."
The above is the detailed content of Are Inline Virtual Functions a Myth, or Just Misunderstood?. For more information, please follow other related articles on the PHP Chinese website!