Reputation: 484
In a CppCon talk by Nicolai Josuttis (see here starting at 34:10), one of his suggestions for the use of the specifiers virtual
, override
, and final
, is to mark either all functions virtual (for a polymorphic class) or none of them (for a standard class).
His rational for doing this is that it allows you to write functions that cannot be overridden or hidden by specifying those functions as virtual
-final
in the base class. He states that the compiler can just inline the function, because it is able to reason that it won't actually be virtual. It's interesting advice, because now each function in the base class means something specific depending on the specifiers you use: must be overridden, can be overridden, or cannot be overridden. It also begs the question, if your derived class can be called without polymorphism, why are you making it polymorphic at all?
Because this seemed like it could work, and some of the audience in the talk seemed to disagree with that advice, I wrote a simple program to test it out (see here). It seems clang is able to inline the function, whereas for g++, the doProcedure()
function ends up in the vtable anyway. Is the compiler required to inline these sorts of functions or could there be performance penalties when you do this?
The basic outline of the test can be seen below, however I am worried that it may be so simple that it is masking the issue.
class Base
{
public:
virtual ~Base() = default;
virtual void doProcedure() const final // Cannot be overridden
{
preProcess();
process();
postProcess();
}
protected:
virtual void preProcess() const; // Can be overridden
virtual void process() const = 0; // Must be overridden
virtual void postProcess() const; // Can be overridden
};
class Derived : public Base
{
public:
virtual void process() const override;
// error: virtual function 'virtual void Derived::doProcedure() const' overriding final function
// void doProcedure() const {}
};
Upvotes: 2
Views: 129
Reputation: 238321
Is the compiler required to inline functions...
No. There are no cases where the compiler would be required by the C++ language to expand a function call inline.
Upvotes: 4