Click here to Skip to main content
15,896,269 members
Articles / Programming Languages / C++

Using Interfaces for Object Oriented Primitives

Rate me:
Please Sign up or sign in to vote.
4.65/5 (11 votes)
7 Dec 20047 min read 57.5K   369   27  
An introduction to the OOTL (Object Oriented Template Library). Describes how the OOTL uses a bleeding-edge technique of defining interface types in C++ to provide lightweight object-oriented primitives with run-time polymorphism through an IObject interface.
void PrintObjectDetails(IObject o) {
  printf("class = %s, size = %d, object-id = %p, class-id = %x\n", o.GetClassName(), o.GetObjectSize(), o.GetObjectId(), o.GetClassId());  
}

void OutputObject(IObject o) {
  PrintObjectDetails(o);
  if (TypeIs<Float>(o)) {
    Float f = *ObjectCast<Float>(o);
    printf("Float = %f\n", f.ToPrimitive());
  }
  else
  if (TypeIs<Dbl>(o)) {
    Dbl d = *ObjectCast<Dbl>(o);
    printf("Dbl = %f\n", d.ToPrimitive());
  }
  else
  if (TypeIs<Char>(o)) {
    Char c = *ObjectCast<Char>(o);
    printf("Char = %c\n", c.ToPrimitive());
  }
  else
  if (TypeIs<Int>(o)) {
    Int i = *ObjectCast<Int>(o);
    printf("Int = %d\n", i.ToPrimitive());
  }
  else
  if (TypeIs<UInt>(o)) {
    UInt i = *ObjectCast<UInt>(o);
    printf("UInt = %d\n", i.ToPrimitive());
  }
  else
  if (TypeIs<Bool>(o)) {
    Bool b = *ObjectCast<Bool>(o);
    if (b) {
      printf("Bool = true\n");
    } else {
      printf("Bool = false\n");
    }          
  }
  else {
    printf("Unsupported type %s", o.GetClassName());
  }
}

struct AbcObject {
  virtual int GetTypeId() = 0;
};

struct AbcInt {
  int GetTypeId() { return 1; }
  int m; 
};

struct AbcFloat {
  int GetTypeId() { return 2; }
  float m;
};

struct AbcChar {
  int GetTypeId() { return 3; }
  char m;
};

struct Baz {
  OOTL_DEF_OBJECT(Baz);
};

void ObjectTest() {
  printf("starting object test ...\n");
  Int i = 42;  
  Float f = static_cast<float>(3.141);
  Char c = 'Q';
  Dbl d; // defaults to 0.0
  Bool b = true;
  UInt u; // defaults to 0
  Baz baz;
  OutputObject(i);
  OutputObject(f);
  OutputObject(c);
  OutputObject(d);
  OutputObject(b);
  OutputObject(u);
  OutputObject(baz);
  printf("... finished object test\n");
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer Ara 3D
Canada Canada
I am the designer of the Plato programming language and I am the founder of Ara 3D. I can be reached via email at cdiggins@gmail.com

Comments and Discussions