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?
If the compiler can deduce the actual type at compile time, it can avoid the virtual function dispatch. But it can only do this when it can prove that the behavior is equivalent to a run-time dispatch. Whether this happens depends on how smart your particular compiler is.
The real question is, why do you care? You obviously understand the rules for calling virtual functions, and the semantics of the behavior are always those of a run-time dispatch, so it should make no difference to how you write your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With