O'Reilly logo

C++ Cookbook by Jeff Cogswell, Jonathan Turkanis, Christopher Diggins, D. Ryan Stephens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required