当派生类为final时,C++虚函数能否被内联?
final? Great question—super relevant for embedded C++ where even tiny runtime overheads can make a big difference. Let's break this down clearly:
Yes! When a derived class is marked final, compilers absolutely can inline virtual function calls, even when you're using a base class pointer or reference to access the object. Here's why:
The final keyword tells the compiler that no further classes can inherit from this derived class. That means if you have a base class pointer pointing to an instance of this final derived class, there's zero ambiguity about which function implementation will be called—there's no possible subclass that could override the function again.
This removes the need for runtime vtable lookup. The compiler can statically resolve the exact function to call, which opens the door for inlining just like any non-virtual function.
Example to Illustrate
class Base { public: virtual void processData() = 0; }; // Marked final—no subclasses allowed class EmbeddedProcessor final : public Base { public: void processData() override { // Optimized embedded-specific logic } }; void handleSensorInput(Base* device) { // Compiler knows device must point to EmbeddedProcessor // (since it's final and no other derived classes exist) // So it can inline processData() directly here device->processData(); }
A Quick Caveat
This optimization depends on your compiler's optimization level (you'll typically need -O2 or -O3 enabled, which is standard in embedded builds focused on performance). Also, if the compiler can't prove that the base pointer/reference definitely points to the final derived class (e.g., if the pointer comes from an external source you can't track at compile time), it won't be able to inline. But in cases where the object's type is statically knowable, final gives the compiler the green light to eliminate that vtable overhead.
For embedded systems, this is a sweet spot: you get the clean abstraction of using base class interfaces, while avoiding the runtime cost of virtual functions when it matters most.
内容的提问来源于stack exchange,提问作者DocValle

