Home > Backend Development > C++ > Are Inline Virtual Functions a Myth, or Just Misunderstood?

Are Inline Virtual Functions a Myth, or Just Misunderstood?

Patricia Arquette
Release: 2024-12-27 06:39:14
Original
170 people have browsed it

Are Inline Virtual Functions a Myth, or Just Misunderstood?

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template