I have already read Are inline virtual functions a real non-sense?. However I have some doubts and located no the solutions there.
They are saying that if situation is not ambiguous, compiler should inline the virtual function.
This could happen only if the compiler comes with an actual object as opposed to a pointer or mention of the an item.
What exactly if I've got a
B class based on an
A one (which consists of a
virtual void doSth() function) and that i make use of the
B* pointer, not the
B* b = new B b->doSth()
- Guess that the
Bhas not any child classes. It's rather apparent (around the compile time) what function ought to be known as. So you can be inlined. Could it be actually?
- Guess that the
Bhas some child classes however these classes haven't its very own
doSth()function. So compiler should "know" the only function to call is
B::doSth(). I suppose it does not inline though?
It does not matter whether
B has any derived classes. For the reason that situation
b indicates a
B object therefore the compiler can inline the phone call.
And surely any decent modern compiler can and is going to do that inside your situation. If you do not use pointers it might be a great deal simpler. It's no "optimisation" then. Because you can omit an online call then becomes apparent by only searching in the AST node in the left side from the
.-operator. But when you utilize pointers, you have to track the dynamic kind of the pointee. But modern compilers can handle that.
EDIT: Some experiment is needed.
// main1.cpp struct A struct B : A void g() // clang -O2 -S -emit-llvm -o - main1.cpp c++filt // ... define void @g()() // ...
As possible seen, clang does direct calls to
f, both when
a indicates a
A so when it indicates a
B. GCC does this too.
An online member function could be inlined once the vtable isn't dereferenced for that call. This can be done by looking into making an clearly scoped call towards the member function.
class A class B : public A B *obj = new B() obj->Func() // Calls B::Func() through vtable obj->A::Func() // Inlines calls to some::Func() obj->B::Func() // Inlines calls to B::Func()