Bilal <
bilal...@googlemail.com> wrote:
> However, some of the definitions available on internet are confusing.
> For example, over a dozen of web resources say "Virtual function call
> is resolved at run-time (dynamic binding) whereas the non-virtual
> member functions are resolved at compile time (static binding)".
The simplest explanation is an example:
//------------------------------------------------------
class Base
{
public:
void func1() const { std::cout << "func1\n"; }
virtual void func2() const = 0;
};
void foo(Base& obj)
{
obj.func1(); // Can be resolved at compile time
obj.func2(); // (Probably) resolved at runtime
}
//------------------------------------------------------
In the first case the compiler can see directly which function
implementation is being called, so it can put a direct function
call there (or even inline the implementation, if it sees it).
In the second case the compiler (usually) cannot know which
implementation will be called, so it uses some runtime logic
to find out. In practice this is just an indirect function call,
which isn't much heavier than a direct one.
(In most/all compiler implementations there's a point at the beginning
of 'obj' pointing to a static table created by the compiler, and at some
specific offset there will be a function pointer that the compiler
uses to make the function call. Each derived class will have its
own such virtual table, and objects of that type will have that
vtable pointer pointing to it.)
An usage example would be:
//------------------------------------------------------
class Derived1: public Base
{
public:
virtual void func2() const { std::cout << "derived1\n"; }
};
class Derived2: public Base
{
public:
virtual void func2() const { std::cout << "derived2\n"; }
};
int main()
{
Derived1 obj1;
Derived2 obj2;
foo(obj1); // will print "derived1"
foo(obj2); // will print "derived2"
}
//------------------------------------------------------
> Finally, is it possible that a virtual member function call is
> resolved at compile-time and not at run-time.
It's theoretically possible, but it doesn't affect the behavior of
the program in any way.