typeid and TypeInfo

Get introduced to the Object classes and the two properties: typeid and TypeInfo.

We'll cover the following

Object

Classes that do not explicitly inherit any class, automatically inherit the Object class.

By that definition, the topmost class in any class hierarchy inherits Object:

// Inherits Object indirectly
class StringInstrument : MusicalInstrument {
    // ...
}

Since the topmost class inherits Object, every class indirectly inherits Object as well. In that sense, every class “is an” Object.

Every class inherits the following member functions of Object:

  • toString: The string representation of the object.

  • opEquals: Equality comparison with another object.

  • opCmp: Sort order comparison with another object.

  • toHash: Associative array hash value.

The last three of these functions emphasize the values of objects. They also make a class eligible for being the key type of associative arrays.

Because these functions are inherited, their redefinitions for the subclasses require the override keyword.

Note: Object defines other members as well. This chapter will include only those four member functions of it.

typeid and TypeInfo

Object is defined in the object module (which is not a part of the std package). The object module defines TypeInfo as well, a class that provides information about types. Every type has a distinct TypeInfo object. The typeid expression provides access to the TypeInfo object that is associated with a particular type. As we will see, the TypeInfo class can be used for determining whether two types are the same, as well as for accessing special functions of a type such as toHash, postblit, etc.

TypeInfo is always about the actual run-time type. For example, although both Violin and Guitar below inherit StringInstrument directly and MusicalInstrument indirectly, the TypeInfo instances of Violin and Guitar are different. They specifically represent Violin and Guitar types, respectively:

Get hands-on with 1200+ tech skills courses.