Thursday, July 30, 2009

"Virtaul" C++ subroutines?

Can someone please explain what the heck "virtual" means when placed in front of a C++ subroutine definitions. I read an online tutorial, bust it just doesn't make sense!

"Virtaul" C++ subroutines?
It means that the declaration of that function is missing. It should be defined by the child objects.





For example if you have a class called geometricobject you can put a virtual function called ComputeArea() withouth writing any code to it. When you define some child classes like triangle or square you need to write specific functions CumputeArea that compute the area.





PS: I think it's called virtual.
Reply:This explanation misses the point that you can pass a child


class to any method expecting a "geometricobject", and the


child's version of "ComputeArea()" will be called. Without


virtual functions, the **parent's** method would be called.





This is what distinguishes virtual from non-virtual. Report It

Reply:There's an excellent description and illustration-by-example


in the wikipedia entry, so please take a look at ref #1.





I'd like to take a shot at a more informal description.





Consider that you define a class called "shape" with a


"print()" method. You might derive a class from it called


"triangle", which would *also* define a "print()" method.





If you declare a "shape" object and call its "print()"


method, you'll get the shape version of print. But what


if you have a pointer to a "triangle" object, and then


assign it to "pointer to shape"? If you call the "print()"


method from that new pointer, the compiler will presume


that it is a "shape". The issue is that at *compile*


time, the type of the object was determined by the type


of the pointer, and that determines the method which


is called.





A virtual function, however, is determined at *run* time.


If the compiler is calling a method from a pointer to


"shape", it knows that it *might* be a "shape", or it


might be a "triangle" (or "square" or "circle" or whatever).


Instead of directly calling the method for type "shape",


it calls through a pointer which is set at runtime when


the object is created.





The reason for this is that you'd like to create a


polymorphic data structure which could hold *any*


subtype of "shape", but have the right thing happen


when each method is called.





So my summary is that "regular" methods are called


based on a compile-time type determination, whereas


"virtual" methods are called based on a run-time


type determination (ie. through a run-time pointer).





Do look at the wikipedia reference.

umbrella plant

No comments:

Post a Comment