View Full Version : Virtual
04-06-2003, 01:19 PM
When should we declare a function "virtual"? Can somebody please give a practical reason?
I've seen this in a lot of OpenGL OO programs and although I know what virtual is, I don't know when one should use it.
04-06-2003, 02:39 PM
That is strictly C++ (or some other OOP language like Java) - nothing to do with OpenGL. But, I'll answer it for you...
Basically, if you have a base class and you want derived classes to be able to override a function definition, then you declare it as virtual. Then, if that function is called from within the object of a derived class it will find the highest level defintion of that function and use it. If you need to, you can use the scope resolution operator (Cbaseorderivedclass::) to call lower level function definitions of that same function.
I recommend that you buy a book on C++ so you can read about it at your leisure and gain a better understanding of the language.
[This message has been edited by shinpaughp (edited 04-06-2003).]
04-07-2003, 05:48 AM
For a slightly more specific example (just because I'm killing time at work) try this:
Let's say you're creating an object heirarchy to represent objects in a game engine. You might want to have a common base class that all other objects derive from we can call it BaseDrawableObject. Now all objects can draw but a BaseDrawableObject has nothing TO draw, its simply a logical representation of the idea that all objects have something in common. In this case you would declare the Draw method in the class to be virtual. Then when we create a SuperMonkeyAvengerModelObject we would override the empty Draw method with the code necessary to draw the SuperMonkeyAvengerModel object.
What does this gain us you might ask? Well if I'm creating my objects dynamically I can hold a pointer to a BaseDrawableObject but instantiate objects that derive from it. Using the base class pointer (I do this when I have an array of drawable objects) I can call the draw method but the derived implementation of the method is what will execute.
That's just one case where using virtual functions in something like OpenGL comes in handy.
04-08-2003, 02:50 PM
J_Kelley_at_OGP thanks for taking the time to type this. Exactly what I was looking for!
You know, most books stay at a theoritical level and you must have a VERY extensive library in order to find a practical explanation like that.
Thanks again http://www.opengl.org/discussion_boards/ubb/smile.gif
Powered by vBulletin® Version 4.2.2 Copyright © 2014 vBulletin Solutions, Inc. All rights reserved.