0

I have just started C++, i have problem in understanding virtual functions. can anybody tells me what are v.f. and most important what is there importance in C++.

Thanks

3
Contributors
2
Replies
3
Views
10 Years
Discussion Span
Last Post by Ancient Dragon
0

Of my studying and understanding, Virtual Functions are used only for polymorphism. Use virtual functions ONLY if you know those functions wil be overloaded or overrided in derived classes. Don't make a habit of using virtual in any function because "you may need to overload it later on". Now, for a member function to be virtual in a class, both the base class AND derived class must be able to be instantiated. This is very important otherwise the entire concept of virtual functions is lost.
So summing up virtual functions are important to C++ as they are the major factor in polymorphism.

0

>>Now, for a member function to be virtual in a class, both the base class AND derived class must be able to be instantiated

Not really. The base class can have pure virtual functions which means it can not be instantiated on its own. The derived class(s) must override pure virtual functions, while it is optional to override the others. A class can have both virtual and pure virtual functions.

>>Don't make a habit of using virtual in any function because "you may need to overload it later on".

Base classes do not always know if the derived classes need to override the virtual functions, so I see no harm in making virtual functions even though the programmer may not know if they are needed or not. I think the main idea here is: does the base class want to allow derived classes to override the function? If yes, then make it virtual.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.