virtual keyword in derived class

#include<iostream>
using namespace std;
class base
{
public:
void fun()
{
cout<<"base";
}
};

class derived : public base
{
public:
virtual void fun()
{
cout<<" derived";
}
};

int main()
{
base *p;
derived d;
p=&d;
p->fun();
return 0;
}


Output : base

could not understand why?
The function is only virtual from the first class it's declared virtual and downwards.

Making a function virtual in the parent makes it virtual in the child....
but
Making a function virtual in the child does not make it virtual in the parent.

Sinec 'p' points to a 'base', and 'fun' is not virtual in base, then when you call p->fun(), you get the base version.
but in this case also vtable will be creating as derived class contain virtual function.

derived class will also have vpointer than why is compiler not able to identify correct function.

As per my understanding about virtual table mechanism, compiler extract two byte from the assigne address ( i.e d (derived class object) ) and look for table. as we have table than it should get vtable and resolve this issue.

Corret me if my understanding is wrong
Assuming base and derived both have vtables, they could both have different vtables.

Here, since fun is not virtual in base, base would not have an entry for fun in its vtable, so there's nothing for it to look up.

Though in this instance, base isn't polymorphic at all, so base doesn't have any vtable.


Really though, this is an over-technical explanation of something that's much more simple. The bottom line is that 'fun' is not virtual in base.
Topic archived. No new replies allowed.