How to Write Abstract Classes in C++
01/21/2013 Leave a comment
When creating abstract classes, you typically only give the bare essentials, something analogous to the outline of a research paper. Generally only function prototypes and the key variables are given. When a class is made abstract, the compiler doesn’t allow you to instantiate it on its own (duh) – it must be inherited.
In C++ any class can be abstract. Unlike java, C++ doesn’t have an obvious way of making the class abstract. You CANNOT USE THE KEYWORD “abstract” before a class name to do this. (For whatever reason, VC++ (Visual Studio C++) changes the color of the words “abstract” and “array” to blue, making people think those are special keywords, but they aren’t. Perhaps those were intended for some future implementation.)
For a class to be abstract, it must contain at least one abstract function – one whose body is defined elsewhere. To make a function abstract, simply end its prototype with “=0” (that’s “equals zero” and without the quotation marks) prior to the semi-colon.
Note that functions whose prototypes are given that are not abstracted (not made virtual, which I’ll explain in a moment) must be given a function body even if it is overridden by another function definition (overriding is only possible with virtual functions).
Functions don’t have to be given a body if they are made virtual (which means dynamic binding – the function body is found during run-time, as opposed to compile time (static binding)). To make a function virtual, precede its prototype by the keyword “virtual”. Virtual functions can be provided a body in the same way as other functions. Note, however, that unless the function body is provided inline (not in another file), the function definition will not be found whenever that name is used or whenever the class is inherited by another class unless you include the cpp file for it at the top of the header file (but below the include for the header file containing the prototypes) for the class that is doing the inheriting. If you fail to include this cpp file and try to use these functions, you will get a linker error (2019 in VC++ 2008).
To make it so that you can redefine a function body, the function needs to be either made abstract (using the =0 technique shown above) or declared as virtual.
Let me make something clear: Using virtual functions does NOT make your class abstract. Hence, you cannot create a class of purely virtual functions, leave the functions undefined (without function bodies), and then inherit from that class. Inheritance requires that those functions be defined somewhere (even if in another included file). Otherwise, you will get a LNK2001 error.