20-CS-122-001 Computer Science II Spring 2012
Topological Sort - No Ifs

Virtual functions, classes, inheritance, lists, queues, stacks, applications

topo_no_if.cc

#include <iostream.h>
#include <stdlib.h>
#include <fstream.h>
#include <string.h>
using namespace std;

class SubassemblyType {
 friend class SubassemblyObject;
 friend class NullObject;
 friend class ErrorObject;
   
   SubassemblyType *current;
   virtual void doit () { }
   
 public:
   virtual void require (SubassemblyType *) { }
   void output_ident () { current->doit(); }
};

class NullObject : public SubassemblyType {
 public:
   NullObject () { current = this; }
};

class ErrorObject : public SubassemblyType {
   void doit () { 
      cout << "\nError - there is a loop\n";
      exit (0);
   }
	
 public:
   ErrorObject () { current = this; }
};

// The following two lines must go here because they depend on
// ErrorObject, NullObject, and SubassemblyType which are defined above
SubassemblyType *error_object = new ErrorObject();
SubassemblyType *null_object  = new NullObject();

class SubassemblyObject : public SubassemblyType {
   SubassemblyType *dependsOn[3];
   char ident[128];
   int count;
   
   void doit () {
      current = error_object;
      dependsOn[0]->output_ident();
      dependsOn[1]->output_ident();
      dependsOn[2]->output_ident();
      cout << " [" << ident << "]";
      current = null_object;
   }
	
 public:
   SubassemblyObject (const char *id) {
      dependsOn[0] = dependsOn[1] = dependsOn[2] = null_object;
      current = this;
      strncpy(ident,id,128);
      count = 0;
   }

   void require (SubassemblyType *sobject) {  dependsOn[count++] = sobject; }
};

int main () {
   // Grab some SubassemblyObject nodes
   SubassemblyType
      *a = new SubassemblyObject("a"),
      *b = new SubassemblyObject("b"),
      *c = new SubassemblyObject("c"),
      *d = new SubassemblyObject("d"),
      *e = new SubassemblyObject("e"),
      *f = new SubassemblyObject("f");
   
   // Set up some dependencies
   a->require(b);
   a->require(f);
   b->require(e);
   b->require(f);
   c->require(a);
   c->require(b);
   e->require(d);
   d->require(f);
   // f->require(a);
   
   // Execute
   a->output_ident();
   b->output_ident();
   c->output_ident();
   d->output_ident();
   e->output_ident();
   f->output_ident();
   
   cout << "\n";
   return 0;
}