what is Virtual? what is it's functionality?Can a variable also a virtual?what is the role of virtual in a program?what is it's advantages and disadvantages or limitation of virtual ? Can also be a class virtual? please help me...
Variable can't be virtual. Virtual is a specifier, that makes polymorphism possible. Take a look at this Q/A: https://www.sololearn.com/discuss/810883/?ref=app In the code OP has two classes: monster and ninja, both derrived from enemy. He creates two objects: n and m of these classes. Then he uses base class pointers e1 and e2 to call the attack method, that is overloaded. Without virtual specifier in the base class's attack, the base class's implementation will be called - it will be determined by the type of the pointer. With virtual, the proper implementation of the derrived class's method will be called - it will be determined by the type of the object the pointer points to. And as for when is this useful, imagine we want to make a program, that draws figures. We may implement all kinds of figures as subclasses of the base class Figure - like Circle, Triangle, Rectangle - each derrived from Figure. To implement the drawing we may create a virtual draw() method for these classes. That will allow us to use a generic Figure pointer to call an overloaded method of the specific figure draw() method. So we may draw any shape without knowing which one it is. Figure *f = new Hexagon(); //... /* Somewhere in the program, where we don't care about the figure type */ f->draw(); Here's a code to illustrate the example with figures: https://code.sololearn.com/c1d6zMqXxQu3/?ref=app
@Gordie, Even though I knew about vtables and stuff, I happened to be unfamiliar with the late/early -binding terms. And, while looking them up, found a good read on this topic: http://www.learncpp.com/cpp-tutorial/124-early-binding-and-late-binding/
One of the disadvantages is performance, virtual functions are placed into an array of function pointers, and so at runtime this can add an overhead along with not being able to be inlined in all cases.