What’s a pure virtual function?

Print anything with Printful



Object-oriented programming has a pure virtual function that acts as a placeholder for other variables and can be changed on a per-user basis. A derived class is needed for it to work. Virtual functions have their own body, while pure virtual functions don’t. Pure virtual functions limit the amount of code the programmer has to create and can be modified to make the program more efficient.

Almost all types of object-oriented programming (OOP), which creates programs and separates sections of code into “objects”, have a function called a pure virtual function, which is different from a virtual function. Also known as an abstract function, a pure virtual function acts as a placeholder for other variables and takes information from other functions and classes to fill in the blanks. The advantage of using a pure virtual function is that the information is malleable and can be changed on a per-user basis. For this to work, a derived class must exist from which data is taken.

A virtual function is similar to the pure variant. Both are able to change depending on user input. For example, if a user types their name, the virtual function will change for the entire program to accommodate that user’s name. The difference is that a virtual function doesn’t depend on other classes, because the virtual function has its own body that passes data to other classes and functions that request the information, in this example the user’s name.

A pure virtual function, by contrast, has no body. This means that, by itself, the abstract function is useless. It has no data of its own, and if the abstract class is called without any information, it may cause an error. The pure virtual function must have a derived class, or a class that collects data for the abstract function, to work.

The derived class can be a question or an area where a user enters some sort of input, such as a text field. The information of this class is then transferred to all connected pure virtual functions, coordinating the responses. Unless the abstract function is specifically called, it will not fire unless there is readily supplied data.

Pure virtual functions have several advantages. Using an abstract function instead of creating an entire body of code substantially limits the amount of code the programmer has to create, especially for large programs that use the same information over and over again. The abstract function can also be modified by the programmer to change the way the program handles data to make it more efficient. The information is based on derived classes, so programs with complex questions and inputs will adjust the data based on user input without the program accidentally calling another irrelevant section of code.




Protect your devices with Threat Protection by NordVPN


Skip to content