8.10. Creating an Interface with an Abstract Base Class
Problem
You need to define an interface that subclasses will implement, but the concept that the interface defines is just an abstraction, and is not something that should be instantiated itself.
Solution
Create an abstract class that defines the interface by declaring at least one of its
functions as pure virtual
. Subclass this abstract class
by clients who will use different implementations to fulfill the same interface
guarantees. Example 8-10 shows how you
might define an abstract class for reading a configuration file.
Example 8-10. Using an abstract base class
#include <iostream> #include <string> #include <fstream> using namespace std; class AbstractConfigFile { public: virtual ~AbstractConfigFile() {} virtual void getKey(const string& header, const string& key, string& val) const = 0; virtual void exists(const string& header, const string& key, string& val) const = 0; }; class TXTConfigFile : public AbstractConfigFile { public: TXTConfigFile() : in_(NULL) {} TXTConfigFile(istream& in) : in_(&in) {} virtual ~TXTConfigFile() {} virtual void getKey(const string& header, const string& key, string& val) const {} virtual void exists(const string& header, const string& key, string& val) const {} protected: istream* in_; }; class MyAppClass { public: MyAppClass() : config_(NULL) {} ~MyAppClass() {} void setConfigObj(const AbstractConfigFile* p) {config_ = p;} void myMethod(); private: const AbstractConfigFile* config_; }; void ...
Get C++ Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.