K
Kapil Khosla
Dear all,
I am trying to underlying implementation of virtual functions in C++.
The way I understand polymorphism is
class Base
{
public:
virtual int func();
};
class Derived: public Base
{
public:
virtual int func();
}
int Base::func()
{
printf("In Base\n");
}
int Derived::func()
{
printf("In Derived\n");
}
void poly_func(Base * x)
{
x->func();
}
int main()
{
Derived ob1;
poly_func(&ob1);
}
Output :
This will call the function in the derived class instead of the base
class due to the virtual keyword in the base class with func().
Now my question is how does C++ implement such mechanism.
I read something about VTables in C++, that every class has a
different VTable which contain the appropriate function to be called.
So by pushing the pointer to the appropriate VTable you can figure out
the function to be called.
They said that at "run time" you would find out which object is really
being called and thus we need VTables. I dont understand this point.
In this case it is pretty obvious that &ob1 is being passed so
compiler can figure out at compile time which real function is to be
called based on the fact that the virtual keyword is there in the base
class. Can you give me an example where the compiler would not be able
to figure out the type of the object being passed at compile time and
thus show me the need of VTables.
I am not very familiar with OOPS concept so might not be aware of some
basic concepts.
Thanks a lot,
Kapil
I am trying to underlying implementation of virtual functions in C++.
The way I understand polymorphism is
class Base
{
public:
virtual int func();
};
class Derived: public Base
{
public:
virtual int func();
}
int Base::func()
{
printf("In Base\n");
}
int Derived::func()
{
printf("In Derived\n");
}
void poly_func(Base * x)
{
x->func();
}
int main()
{
Derived ob1;
poly_func(&ob1);
}
Output :
This will call the function in the derived class instead of the base
class due to the virtual keyword in the base class with func().
Now my question is how does C++ implement such mechanism.
I read something about VTables in C++, that every class has a
different VTable which contain the appropriate function to be called.
So by pushing the pointer to the appropriate VTable you can figure out
the function to be called.
They said that at "run time" you would find out which object is really
being called and thus we need VTables. I dont understand this point.
In this case it is pretty obvious that &ob1 is being passed so
compiler can figure out at compile time which real function is to be
called based on the fact that the virtual keyword is there in the base
class. Can you give me an example where the compiler would not be able
to figure out the type of the object being passed at compile time and
thus show me the need of VTables.
I am not very familiar with OOPS concept so might not be aware of some
basic concepts.
Thanks a lot,
Kapil