Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page