November 2005
Beginner to intermediate
594 pages
16h 23m
English
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.
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 ...