I am confused with VTable ;-)

P

Pani

Hi
I am new to C++ ,i really dont understand why there is a need for
VTable and can some experts give an example where exactly and how a compiler
uses it

Regards
Pani
 
J

John Harrison

Pani said:
Hi
I am new to C++ ,i really dont understand why there is a need for
VTable and can some experts give an example where exactly and how a compiler
uses it

Regards
Pani

Caution, this example may imply certain views about the theory of evolution
for which the author is completely irresponsible.

#include <iostream>
using namespace std;

class Ape
{
public:
virtual void what_am_i() { cout << "i'm an ape\n"; }
};

class Human : public Ape
{
public:
virtual void what_am_i() { cout << "i'm an human\n"; }
};

int main()
{
Ape* ape1 = new Ape();
Ape* ape2 = new Human();
ape1->what_am_i();
ape2->what_am_i();
}

Would you want to be mistaken for an ape?

Although ape2 has type Ape*, it is pointing to a Human object and therefore
a Human vtable. So the compiler uses the Human vtable to call
Human::what_am_i().

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top