Possible Duplicate:
Can someone explain C++ Virtual Methods?
I have a question regarding to the C++ virtual functions.
Why and when do we use virtual functions? Can anyone give me a real time implementation or use of virtual functions?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You use virtual functions when you want to override a certain behavior (read method) for your derived class rather than the one implemented for the base class and you want to do so at run-time through a pointer to the base class.
The classic example is when you have a base class called
Shapeand concrete shapes (classes) that derive from it. Each concrete class overrides (implements a virtual method) calledDraw().The class hierarchy is as follows:
The following snippet shows the usage of the example; it creates an array of
Shapeclass pointers wherein each points to a distinct derived class object. At run-time, invoking theDraw()method results in the calling of the method overridden by that derived class and the particularShapeis drawn (or rendered).The above program just uses the pointer to the base class to store addresses of the derived class objects. This provides a loose coupling because the program does not have to change drastically if a new concrete derived class of
shapeis added anytime. The reason is that there are minimal code segments that actually use (depend) on the concreteShapetype.The above is a good example of the Open Closed Principle of the famous SOLID design principles.