Implementing pure virtual functions

January 09, 2013

Dan_Saks-January 09, 2013

Implementing pure virtual functions as null pointers is simple but probably not robust enough for most applications.

Last year, I wrote several columns on how virtual functions behave in C++ and how you can obtain similar behavior in C. In short, you can emulate a polymorphic C++ class (a class with at least one virtual function) as a C structure that has an additional member commonly called a vptr (VEE-pointer).[1] The vptr points to a table of function pointers called a vtbl (VEE-table).

Last month, I introduced the concept of pure virtual functions in C++.[2] This month, I'll show how compilers typically implement pure virtual functions by showing how you can achieve similar behavior in C.

As in my prior articles, my sample classes represent an assortment of two-dimensional geometric shapes such as circle, rectangle, and triangle, all derived from a common base class called shape. The C++ definition for the shape base class looks in part like:

class shape {
public:
   shape(color o, color f);        // constructor
   virtual double area() const = 0;
   virtual double perimeter() const = 0;
   ~~~
   
private:< 
   color outline, fill;
};


The characters = 0 appearing at the end of the declarations for area and perimeter indicates that they are pure virtual functions. They need not be defined. As I asked at the end of my previous column, if shape's area and perimeter functions are undefined, what happens when you try to call them?




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

< Previous
Page 1 of 3
Next >

Loading comments...

Most Commented

Parts Search Datasheets.com

KNOWLEDGE CENTER