In C++, during dynamic binding, consider the following example...
class Base
{
virtual void fun()
{
cout<<"Base";
}
};
class Derived : public Base
{
void fun()
{
cout<<"Derived";
}
};
int main()
{
Base *bptr;
Derived d;
bptr=&d;
bptr->fun();
return 0;
}
The output of the above C++ program is "Derived" due to the declaration of virtual keyword/dynamic binding.
As per my understanding, a virtual table (Vtable) would be created which contains the address of the virtual functions. In this case the virtual table created for the derived class points to the inherited virtual fun()
. And bptr->fun()
will be getting resolved to bptr->vptr->fun();
. This points to the inherited base class function itself. I am not completely clear on how the derived class function is called?
int main
, notvoid main
, and class declarations need to end with a;
. – Trixie