Virtual Function vs Pure Virtual Function: Key Differences Explained

A virtual function is a C++ member marked virtual that can be overridden in derived classes; it may have a body. A pure virtual function adds = 0, making the class abstract and forcing subclasses to supply their own implementation.

People mix them up because both sit in base classes and enable polymorphism. Yet the everyday confusion arises when coders forget the = 0 and suddenly find themselves able to instantiate a class they intended to keep abstract.

Key Differences

Virtual: has a body, lets you create objects of the base class, default behavior provided. Pure virtual: no body, base class becomes abstract, subclasses must implement; otherwise compilation fails.

Which One Should You Choose?

Use virtual when the base offers sensible default behavior. Choose pure virtual when the base should never be instantiated and every derived type must define its own version of the method.

Examples and Daily Life

Think of a generic Vehicle with startEngine(). If you can start it without customization, keep it virtual. If ElectricCar, GasCar, etc., must each define unique starting logic, make startEngine() pure virtual to force the design.

Can a class have both virtual and pure virtual functions?

Yes. The class stays abstract if at least one function is pure virtual.

What happens if I forget to implement a pure virtual function in a subclass?

The subclass itself becomes abstract and cannot be instantiated.

Is there a performance cost to virtual vs pure virtual calls?

Both use v-table dispatch; the difference is negligible, so choose based on design, not speed.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *