Erik Wikström
11/21/2008 5:56:00 PM
On 2008-11-21 15:23, want.to.be.professer wrote:
> For OO design, I like using virtual member function.But considering
> efficiency, template is better. Look at this program,
> Virtual member function will make our object adding a virtual table
> pointer( size: 4 ).When using Virtual member function, computer must
> read the pointer value, and then find the virtual table.
> Using template , you call the Walk(), and then WalkMe() is called, So
> It is also two times. Some books say virtual function will Impact on
> the efficiency of program, so I cannot understand( In this program,
> they both 2 times ). In this program, which is the better one
> ( efficiency )?
Virtual functions and templates serves different purposes, you only need
virtual functions when you do not know the exact type while your are
writing the code (i.e. the type will be determined at run-time), while
templates are used when you do know the exact type at compile-time.
Virtual functions do come with a slight penalty but in most cases it is
negligible. A rule of thumb is to not make functions virtual unless you
have to (i.e. you need to override them in a derived class) but don't be
afraid to do so when you have to.
--
Erik Wikström