NetApp Interview Question
Software Engineer / DevelopersI think this is correct! Even Learncpp.com also suggest the same reason. Just to rephrase it, we assign derived class objects to base class pointers so that we have a generic way of accessing all derived objects. But this limits the access to base class part of information in the derived class objects. In order to have base class pointers access derived class data access in the derived class objects assigned to it, we use virtual function!
To reuse the code of object, we need inheritance. By upcasting an object of the derived class to a pointer of the base class, that object can be used wherever the base class can be used. However, this object would still perform as one of the base class without polymorphism (i.e., virtual function). In order for the object of the derived class to behave as the derived class, we need to use "virtual function".
In summary, reuse of object code --> inheritance --> upcasting --> polymorphism (virtual function).
Sole purpose of having virtual functions is code maintenance and nothing else.
- ankit.batra11 March 27, 2012Suppose you wrote a code which is based on calling virtual functions of a base class, that code will be independent of how many classes you derive from the base (but will have the power of calling newer derived versions of the virtual functions) and hence better the code maintainability.