Code Fragment: Object1



class Object {						// generic object
public:
  virtual ~Object() { }					// virtual destructor
  int      intValue()    const throw(BadCastException);	// get integer value
  string   stringValue() const throw(BadCastException);	// get string value
};

class Integer : public Object {				// integer object
private:
  int value;						// integer value
public:
  Integer(int v = 0) { value = v; }			// constructor
  int getValue() const { return value; }		// get the value
};

class String : public Object {				// string object
private:
  string value;						// string value
public:
  String(const string& v = "") { value = v; }		// constructor
  string getValue() const { return value; }		// get the value
};
							// get Integer's value
int Object::intValue() const throw(BadCastException)
{
  const Integer* p = dynamic_cast<const Integer*>(this);
  if (p == NULL) throw BadCastException("intValue() from non-Integer");
  return p->getValue();
}
							// get String's value
string Object::stringValue() const throw(BadCastException)
{
  const String* p = dynamic_cast<const String*>(this);
  if (p == NULL) throw BadCastException("stringValue() from non-String");
  return p->getValue();
}