Interface classes
An interface class is a class that has no members variables, and where all of the functions are pure virtual! In other words, the class is purely a definition, and has no actual implementation. Interfaces are useful when you want to define the functionality that derived classes must implement, but leave the details of how the derived class implements that functionality entirely up to the derived class.
Interface classes are often named beginning with an I. Here’s a sample interface class:
view source
print?
1.class IErrorLog
2.{
3. virtual bool OpenLog(const char *strFilename) = 0;
4. virtual bool CloseLog() = 0;
5.
6. virtual bool WriteError(const char *strErrorMessage) = 0;
7.};
So far, all of the virtual functions we have written have a body (a definition). However, C++ allows you to create a special kind of virtual function called a pure virtual function (or abstract function) that has no body at all! A pure virtual function simply acts as a placeholder that is meant to be redefined by derived classes.
To create a pure virtual function, rather than define a body for the function, we simply assign the function the value 0.
view source
print?
01.class Base
02.{
03.public:
04. const char* SayHi() { return "Hi"; } // a normal non-virtual function
05.
06. virtual const char* GetName() { return "Base"; } // a normal virtual function
07.
08. virtual int GetValue() = 0; // a pure virtual function
09.};
When we add a pure virtual function to our class, we are effectively saying, “it is up to the derived classes to implement this function”.
Monday, August 17, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment