I see in various online resources that virtual functions
are runtime bound.
However a pure virtual function
must be implemented in a derived class. So, it doesn't make sense to me why a vtable
would be needed in that scenario. Therefore I was wondering if a pure virtual function
is bound at runtime or compile time.
If it is bound at runtime, is it just for the case that a pure virtual function
has an implementation and the derived class calls the base implementation? What happens if no implementation is provided? Does the compiler then inline
the implementation?
As you already found out, virtual functions are resolved at runtime. You need a vtable for this situation:
class Parent {
public:
virtual void pure() = 0;
};
class Child : public Parent {
public:
void pure() {}
};
void do_pure(Parent& x){
x.pure();
}
int main(){
do_pure(Child());
}
The Child()
instance is cast to a Parent
when it is passed to do_pure
. The vtable is then required for the line x.pure()
to be able to locate the memory adress of the implementation of pure()
.
If Child
wouldn't implement do_pure
, this wouldn't compile, because the line x.pure()
could only crash.