Pergunta

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.

Foi útil?

Solução

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

Outras dicas

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.

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top