Saturday, June 12, 2010

Pure Virtual Functions

Pure virtual functions should be used;
  • to create an abstract object that is not supposed to be instantiated
  • to force a compile time check of the derived classes to confirm it has implemented the function

#include <iostream>
using namespace std;

class Base
{
public:
  virtual void print_me() = 0;
};

class DerivedBad : public Base
{
public:
  
};

class DerivedGood : public Base
{
public:
  virtual void print_me() { cout << "I am Good" << endl; };  
};

int main()
{
  //Base* a = new Base();       //BAD it has a pure virtual function and is therefoe an abstract class.
  //Base* b = new DerivedBad(); //BAD it fails to implement print_me
  Base* c = new DerivedGood(); //GOOD it fully implements the interface to Base
  c->print_me();

  delete c;
}

No comments:

Post a Comment