virtual table memory

Dec 8, 2012 at 10:38am
http://en.wikipedia.org/wiki/Virtual_method_table

Because the type of object pointed to by the Cat pointer is not determined at compile-time, the decision as to which branch to take cannot be decided at compile-time.


I really want to know why is that so ?

I mean If all the the virtual function has been overriden in derived class then why does it need room for a pointer to a function. Basicly there could only be 1 possiblity.

Dec 8, 2012 at 10:51am
Well, take this example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Cat* createCat()
{
  switch(rand()%2)
  {
    case 0: return new HouseCat();
    case 1: return new Lion();
  }
}  

int main()
{
  Cat* cat=createCat();
  cat->speak();
  delete cat;
}


There's more than one possibility for speak() now, isn't there?
Last edited on Dec 8, 2012 at 10:52am
Dec 8, 2012 at 11:03am
OOk, I think I get it
but what if I don't want that kind of thing

Should I use copy and paste instead of inheritance
because I don't think I can override a non-virtual function
Dec 8, 2012 at 11:04am
but what if I don't want that kind of thing

What kind of thing?

Should I use copy and paste instead of inheritance

I don't really know what you mean, but the answer is no in any case.
Dec 8, 2012 at 11:06am
You have to decide what paradigm you're using; procedural programming, abstract data types, object oriented programming.

Once you've decided what parts of the program are using what, you have to follow the rules of that paradigm. If you are not doing object oriented programming, then don't do it.

The vtable mechanism is part of the object oriented support in C++. If you're not using OO, you won't be using such things.
Dec 8, 2012 at 11:11am
Suppose I am trying to not waste memory

I have a class which is inherited trough so many class. Let's say I have a class that have 50 virtual function. That makes it 200 Byte big without anything else... Let's call it "Cat"

All the function from the where Cat has inherit has been overriden.

suppose anywhere in the code there won't be other than

 
Cat * p = new Cat();


There won't be

 
Animal * x = new Cat();


Dec 8, 2012 at 11:15am
Each object instance has at most one pointer to the virtual function table of its class. You're not wasting any memory.
Besides, if you think you don't need virtual functions, then just don't use them.
Last edited on Dec 8, 2012 at 11:16am
Dec 8, 2012 at 11:16am
So if it's 5 inheritance deep it would only waste 5 pointer ??? is that what you are trying to say ??
Dec 8, 2012 at 11:18am
No, it's at most one pointer per object (at least as long as no multiple inheritance is involved). It is irrelevant how deep your inheritance tree is.
Last edited on Dec 8, 2012 at 11:25am
Dec 8, 2012 at 11:19am
Oh Ok Thanks for your help
Topic archived. No new replies allowed.