virtual function

Hi, sorry if this isn't in the right forum. Anyways, I have a simple question about virtual functions.

When you have a base class that contains a virtual method with several derived classes which all have the same method name, how does the compiler know which one is being called?

In other words, when a virtual member function is activated, how does the compiler choose the correct version.
You need to learn about the concepts of Virtual table and virtual pointers for to understand it.

In general, a virtual table contains addresses of virtual functions. The compiler creates VTABLE for each class that contains virtual functions and also for the classes that are derived from it.

Whenever we create an object of such class, the class gets loaded into memory and virtual table gets created and it's address gets stored in first two bytes of the object. So depending upon the type of object, compiler knows which virtual function is to be called.

I hope this helps :)
When you declare a virtual function in a class the compiler creates a vtable (virtual table for that class). Every function of that class that is declared as virtual gets added to this table. This table contains pointers to functions, the functions which you have implemented in some class. At runtime, when a virtual method is called, a lookup in this vtable is performed that calls the function pointed to by the appropriate element in this table based on the object dispatching the request.

Disclaimer: I've given a general statement and have omitted some minor details in order to not detract from the point I'm trying to make.

Edit: oops incognito got around to it first.
Last edited on
Topic archived. No new replies allowed.