Hello, I expect the compiler to throw an error because virtual functions are defined in both the super and sub classes but it doesn't. Even if that isn't so, I expect the result to be "Fun is derived, x = GV" but it prints x = 0.
Could someone please explain why its happening like this, and what's happening in the vtable implementation behind the scenes since there are two virtual functions defined now. Vtables are defined on the super class - so I don't understand what might be happening in this case..
#include <iostream>
usingnamespace std;
class Base {
public:
virtualvoid fun ( int x = 0 ) {
cout << "Fun in base, x = " << x << endl;
}
};
class Derived : public Base {
public:
virtualvoid fun ( int x ) {
cout << "Fun in derived, x = " << x << endl;
}
};
int main() {
Derived d1;
Base *bp = &d1;
bp->fun();
return 0;
}
void fun(int x = 3) and keep fun() in Base class as virtualvoid fun(int x = 0)
The output becomes "Fun in derived, x = 0".
In the case pointed in the original question, it prints "Fun in derived, x = 0.
I just want to know the mechanics behind this output and its associated implementation in the vtable.
Finally GV = Garbage Value
@dhayden Thanks for the link - that explained what I wanted to know concisely.
I just want to know the mechanics behind this output and its associated implementation in the vtable.
On line 18 thei compiler generates code that calls the fun(...) of the Base class including the default parameter (i.e. 0). It doesn't care that behind the scenes the pointer to the function is replaced by that of fun(...) of the Derived class.
The replacement of the virtual function pointer happens at runtime. Before the body of the derived class is called. Thus when you call fun(...) within the constructor of the Base class you won't call fun(...) of the Derived class.
#include <iostream>
usingnamespace std;
class Base
{
public:
virtualvoid fun ( int x = 0 ) {
cout << "Fun in base, x = " << x << endl;
}
};
class Derived : public Base
{
public:
virtualvoid fun ( int x = 999 )
{
cout << "Fun in derived, x = " << x << endl;
}
};
int main()
{
Derived d1;
d1.fun();
Derived *dp = &d1;
dp -> fun();
Base *bp = &d1;
bp->fun();
// ERROR
// Base b1;
// Derived *db = &b1;
// b1 -> fun();
return 0;
}
Fun in derived, x = 999
Fun in derived, x = 999
Fun in derived, x = 0
Program ended with exit code: 0