1

And why don't we use the same method for non virtual functions?

I mean, why do we use virtual functions in that way? Can't we just use them as non-virtaul ones and override them?

And if this method is saving us time/space or what ever, why don't we use the same method for non-virtual functions? I mean it would make sense that there would be one table of functions for a specific class.

Anyway, thanks in advance, I am just a bit confused.

GMan
  • 81
  • 7

3 Answers3

6

You can't have run-time polymorphism without using a level of indirection. That's what the vptr is for.

The vptr is not used for non-polymorphic functions because that indirection costs something. The C++ philosophy is that you don't pay for what you don't use.

EDIT:

Here's some info on how virtual tables work: http://en.wikipedia.org/wiki/Virtual_table

Fred Larson
  • 60,987
  • 18
  • 112
  • 174
  • Where can I find more information on the another level of indirection for run-time polymorphism? EDIT: And on the C++ philosophy for that matter? Thanks! – GMan Dec 20 '10 at 17:44
  • 1
    @GMan, just try to get the same behaviour using C, you will most likely end up using tables of function pointers. – doron Dec 20 '10 at 17:56
  • 2
    @GMan: From the C++ origianl design doc: http://www2.research.att.com/~bs/rules.pdf That is, the zero-overhead principle: “what you don’t use, you don’t pay for” – Martin York Dec 20 '10 at 20:55
  • @Martin York: Great link. Thank you! – Fred Larson Dec 20 '10 at 21:14
2

The compiler essentially generates a direct call to non-virtual methods. With a virtual method call, the compiler generates code to lookup the address of the method and then makes a call to that address. Thus, it is, in theory, at least one more lookup when calling a virtual function. There would be no reason to incur that cost otherwise.

Mark Wilkins
  • 40,729
  • 5
  • 57
  • 110
2

Using vptr allows method resolution based on object type rather than variable type. Not using vptr makes method calls faster. The C++ designers decided to allow the convenience of virtual functions but not require the performance penalty for other functions.

OrangeDog
  • 36,653
  • 12
  • 122
  • 207