Thursday, April 26, 2012

C++ Virtual Functions and Interface Functions


Wow this is a pretty good review. The key hack syntax for a pure virtual function is

virtual int GetValue() = 0; // a pure virtual function

The way to remember this is that it is declaring a zero pointer, to be defined later. It does not use a special keyword.

Any class that declares even one pure virtual function become an abstract class - you can't make any instances of it, you can only build other classes with it.

Interface Class

The other interesting thing are Interface classes. This was on an interview question I got not long ago.  C# and Java support interfaces which specify method signature, but no code and no data. This is a way to share signatures without sharing any code or data, and gives some of the power of multiple inheritance without the problems. All an interface class is a class that declare no data, and every method is declared pure virtual. That way, the class must implement every method, but does not share data or code with any other class.

Interface classes are often named beginning with an I. Here’s a sample interface class:
class IErrorLog
    virtual bool OpenLog(const char *strFilename) = 0;
    virtual bool CloseLog() = 0;
    virtual bool WriteError(const char *strErrorMessage) = 0;

No comments: