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

Recommended Answers

All 2 Replies

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.

>>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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.