Thread: Point of Virtual

  1. #1

    Point of Virtual

    what is the point of virtual? I understand the ideas of inheritance and overridding functions. however, if one wanted to use the function in the base class, why wouldn't one just declare an example of the base class instead of a derived class? Got what I am saying?

  2. #2
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    It allows the correct methods to be called depending on what type of object it is. You could have a list or array of base class pointers that point to different derived types, call the same method for all objects and the derived method will be called.

  3. #3
    Say you had a base class Shape, with derived classes Circle, Square, Triangle. Each derived class needs to be able to draw itself.
    You could write 3 complete separate draw functions called circleDraw, squareDraw and triangleDraw and just call those. You would have to know which function to call at compile time, however. You couldn't choose which function to call at run time (at least w/o a bunch more code), which you may want/need to do for some reason (e.g., random calls, user input calls, etc that respond to the specific circumstance at run time).
    Also, say each draw function does x, y and z, while Circles also do a, Squares also do b, Triangles also do c.
    Calling the base class Shape function draw allows code in common (x, y, z) to be written only once, and the correct draw function to be called for Circle, Square and Triangle for the unique code (a, b, c). Their functions are also called draw, not circleDraw, etc, in this case. This is done at runtime now.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 48
    Last Post: 09-26-2008, 03:45 AM
  2. rotating around object (looat)
    By jabka in forum Game Programming
    Replies: 13
    Last Post: 06-18-2008, 05:02 PM
  3. Class warfare
    By disruptivetech in forum C++ Programming
    Replies: 13
    Last Post: 04-22-2008, 01:43 PM
  4. Header files and classes
    By disruptivetech in forum C++ Programming
    Replies: 5
    Last Post: 04-21-2008, 09:02 AM
  5. Exporting Object Hierarchies from a DLL
    By andy668 in forum C++ Programming
    Replies: 0
    Last Post: 10-20-2001, 01:26 PM