C++ examples for Class:Virtual Function
Creating an Interface with an Abstract Base Class
#include <iostream> #include <string> #include <fstream> using namespace std; class MyAbstractClass { public://from w w w . j a va 2s . c om virtual ~MyAbstractClass() {} 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 MyConfigFile : public MyAbstractClass { public: MyConfigFile() : in_(NULL) {} MyConfigFile(istream& in) : in_(&in) {} virtual ~MyConfigFile() {} 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 MyAbstractClass* p) {config_ = p;} void myMethod(); private: const MyAbstractClass* config_; }; void MyAppClass::myMethod() { string val; config_->getKey("Foo", "Bar", val); // ... } int main() { ifstream in("foo.txt"); MyConfigFile cfg(in); MyAppClass m; m.setConfigObj(&cfg); m.myMethod(); }