Implementing pure virtual functions
Unfortunately, compilers may fail to catch some pure virtual function calls. Such failures are rare, but nevertheless possible. As a second line of defense, if a pure virtual function has no definition, most compilers generate a definition for that function that makes a stink if executed. The C code to do this for theshape class might look like:double shape_area(shape const *s) {
pure_virtual_alert();
return 0;
}
double shape_perimeter(shape const *s) {
pure_virtual_alert();
return 0;
}
~~~
shape_vtbl the_shape_vtbl = {
shape_area,
shape_perimeter
};
On a desktop system, the
pure_virtual_alert function might simply write a message to the system's stderr stream or display a message box, and then terminate the program. For an embedded system, you would have to tailor the response to be something more appropriate.Dan Saks is president of Saks & Associates, a C/C++ training and consulting company. For more information about Dan Saks, visit his website at www.dansaks.com. Dan also welcomes your feedback: e-mail him at dan@dansaks.com..
Endnotes:
[1] Saks, Dan, "Virtual functions in C," Embedded.com, August 8, 2012. www.embedded.com/4391967.
[2] Saks, Dan, "Pure virtual functions," Embedded.com, December 12, 2012. www.embedded.com/4403313.


Loading comments... Write a comment