I’ve searched for questions, looking at forums, books, etc. I can recognize a polymorphic behavior of methods, and there are lots of simple examples when an invoked method is decided in compile or runtime. But I was confused by this code, where a class C inherits from B that inherits from A:
class A {
protected:
int x;
public:
virtual void change() = 0;
virtual void change(int a) { x = a; }
};
class B : public A {
public:
void change() { x = 1; }
};
class C : public B {
public:
void change() { x = 2; }
void change(int a) { x = a*2; }
};
int main () {
B *objb = new B();
C *objc = new C();
A *obja;
objb->change();
obja = objc;
objc->change();
obja->change(5);
// ...
}
Many examples tells (and it is clear) that a polymorphic behavior occurs and it is decided in runtime what method to call when the following line is executed:
obja->change(5);
But my questions are:
-
What happens when I call the following (overrided from a pure virtual)?
objb->change(); -
What happens when I call the following (overrided from a virtual, but non-pure)?
objc->change(5);
Since the class declaration of the pointer variables are the same of the objects, should the method calling be decided at compile or runtime?
calls
B::change()becauseobjbcontains address of an object of typeBcalls
C::change(int)becauseobjccontains address of an object of typeCThe method calling will be still dynamic/run time because the methods
B::change()&C::change(int)are still virtual, because the virtual attribute in inherited.To answer the question of whether the functions are dynamically dispatched or at compile time
The answer is No can definitely say whether it will be a compile time dispatch or dynamic dispatch. The dynamic/run time dispatch takes place in the first place because the compiler cannot definitely decide which versions of the functions to call at compile time, So if a compiler can deduce a definite manner as to which function to call, the dispatch might very well be decided at compile time itself.
Having said so, whether the dispatch happens at run time or compile time does not change the semantics of calling which version of overidden function gets finally called because the C++ standard explicitly states the rules of which functions of functions in this regard.