TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: Neil Heller
from: David Noon
date: 2003-03-02 19:28:02
subject: Virtual ?

Hi Neil,

Replying to a message of Neil Heller to All:

 NH> Why is the keyword "virtual" a necessity?  It seems to me that C++ 
 NH> programs operate correctly without it (or maybe I just haven't been 
 NH> bitten by the beast yet).  The only place I routinely use the keyword 
 NH> "virtual" is in the header of destructors.  In shops where I've
 NH> worked I  have never seen "virtual" used at all.

 NH> Just wondering... what can't I do by not using "virtual"?
 I can see
 NH> the  reasoning for "pure virtual", but "virtual"?

The virtual qualifier affects the linkage for calling the method.

When the class involved is part of an inheritance hierarchy, any virtual
method is invoked by a lookup in the virtual methods table associated with
the object instance used for the call. This ensures that the implementation
of the method is specific to the exact class of object, not simply of the
declared class. The reason for this is that the instance does not have to
be of the declared class, but can be of any class descended from that
declared class.

This is especially important where destructors are involved, as it ensures
that the clean-up sequence is exactly correct in a delete operation. This
prevents memory leaks.

If you are confused by something as fundamental to OOP as virtual methods,
you should perhaps read Stroustrup ("The C++ Programming
Language"). He explains the whys and wherefores of virtual methods
quite fully.

Regards

Dave


--- FleetStreet 1.25.1
* Origin: My other computer is an IBM S/390 (2:257/609.5)
SEEN-BY: 633/267 270
@PATH: 257/609 250/501 140/1 106/2000 633/267

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.