开发者

Virtual calls in inheritance

How would i know if call to a function is resolved at compile-time or run-time from any class?

For example - In the following, From Derived class when show() is called, would it be resolved at runtime?

#include <iostream>
开发者_StackOverflow中文版using std::ostream;

class Base 
{
public:
    virtual void show() {

         show(); //Call derived class 'show()'
    }
};

class Derived : public Base {

public:

    void show() {

         show(); //Call to itself, Would this call be resolved at run-time?
    }
};

ostream& operator <<(ostream &os, Base &obj)
{

    obj.Base::show();
    return os;
}

int main()
{
    Derived D;

    cout << D << endl;
}


Whenever you are calling a member function through an object of the concrete type (i.e. no pointer), the static type is known thus the compiler resolves the right function at compile time. The only time virtual functions are resolved at runtime is when you are calling them on a pointer to an object, using polymorphism.

In your example the calls to show() are made through the "this" pointer and subsequently they would be resolved at runtime. Consider that there could always be a class even further down the inheritance chain that implements show().

The explicitly qualified call "obj.Base::show()" is obviously resolved at compile time.


Whenever the compiler can figure out which overload of your function to call, it will. It is guaranteed to be able to do that when

  • it has the complete type of the object (e.g. Foo foo; foo.bar();)
  • you tell it which overload to call (e.g. Foo foo; foo.Bar::bar();)

but it may be able to do that in cases where it's less obvious - i.e. if it can figure out that "this pointer to Foo really always points to Bar". That's called devirtualization and is part of the night goggles an optimizing compiler has. Depending on your compiler, and depending on your real-world code, it may be possible to perform this optimization - and call your function directly without passing through the vtable.


To answer your question, in your code obj.Base::show() is being resolved at compile time because of the explicit call to the Base function. If you want to resolve this at run time then you can use a pointer to the Base and pass to it a pointer to a Derived.

For example:

ostream& operator <<(ostream &os, Base *obj)
{    
    obj->show();
    return os;
}

int main()
{
    Derived D;    
    cout << &D << endl;
}

I am not sure what you are trying to do. From your code it seems that you want to call the derived (polymorphic, resolved at runtime version) from your base class 'show()' function. There is no need for this since the Derived version is automatically called because it is virtual.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜