What is a pure virtual function?
A pure virtual function is a function declared within a class and marked with virtual
and = 0
. It has no implementation in the base class and must be implemented in all derived classes.
Why do we need pure virtual function?
A pure virtual function is a way to ensure that all related classes must have a specific function, but each can do it in its unique way. For example, in a zoo, every animal can make a sound, but the sound differs: a dog barks, a cat meows, and a bird chirps. We create a rule in the base class (like "Animal") that says, "Every animal must know how to make a sound." This rule is the pure virtual function. It ensures that any new animal added, like an elephant or a lion, must have its own way of making a sound, keeping everything organized and consistent.
Example of abstract class with pure virtual function
Below is a practical example of using an abstract class: