Jump to content

Run-time type information

From Wikipedia, the free encyclopedia

Template:Short description In computer programming, run-time type information or run-time type identification (RTTI)[1] is a feature of some programming languages (such as C++,[2] Object Pascal, and Ada[3]) that exposes information about an object's data type at runtime. Run-time type information may be available for all types or only to types that explicitly have it (as is the case with Ada). Run-time type information is a specialization of a more general concept called type introspection.

In the original C++ design, Bjarne Stroustrup did not include run-time type information, because he thought this mechanism was often misused.[4]

Overview

In C++, RTTI can be used to do safe typecasts using the <syntaxhighlight lang="cpp" inline>dynamic_cast<T></syntaxhighlight> operator, and to manipulate type information at runtime using the <syntaxhighlight lang="cpp" inline>typeid</syntaxhighlight> operator and std::type_info class, which itself stores the runtime information. In Object Pascal, RTTI can be used to perform safe type casts with the <syntaxhighlight lang="pascal" inline>as</syntaxhighlight> operator, test the class to which an object belongs with the <syntaxhighlight lang="pascal" inline>is</syntaxhighlight> operator, and manipulate type information at run time with classes contained in the RTTI unit[5] (i.e. classes: TRttiContext, TRttiInstanceType, etc.). In Ada, objects of tagged types also store a type tag, which permits the identification of the type of these object at runtime. The <syntaxhighlight lang="ada" inline>in</syntaxhighlight> operator can be used to test, at runtime, if an object is of a specific type and may be safely converted to it.[6]

RTTI is available only for classes that are polymorphic, which means they have at least one virtual method. In practice, this is not a limitation because base classes must have a virtual destructor to allow objects of derived classes to perform proper cleanup if they are deleted from a base pointer.

Some compilers have flags to disable RTTI. Using these flags may reduce the overall size of the application, making them especially useful when targeting systems with a limited amount of memory.[7]

C++ typeid operator

Template:See also The <syntaxhighlight lang="cpp" inline>typeid</syntaxhighlight> keyword is used to determine the class of an object at runtime. It returns a reference to std::type_info object, which exists until the end of the program.[8] The use of <syntaxhighlight lang="cpp" inline>typeid</syntaxhighlight>, in a non-polymorphic context, is often preferred over <syntaxhighlight lang="cpp" inline>dynamic_cast<T></syntaxhighlight> in situations where just the class information is needed, because <syntaxhighlight lang="cpp" inline>typeid</syntaxhighlight> is always a constant-time procedure, whereas <syntaxhighlight lang="cpp" inline>dynamic_cast</syntaxhighlight> may need to traverse the class derivation lattice of its argument at runtime.Template:Citation needed Some aspects of the returned object are implementation-defined, such as std::type_info::name(), and cannot be relied on across compilers to be consistent.

A std::bad_typeid exception are thrown when the expression for <syntaxhighlight lang="cpp" inline>typeid()</syntaxhighlight> is the result of applying the unary * operator on a null pointer. Whether an exception is thrown for other null reference arguments is implementation-dependent. In other words, for the exception to be guaranteed, the expression must take the form <syntaxhighlight lang="cpp" inline>typeid(*p)</syntaxhighlight> where p is any expression resulting in a null pointer.

The <syntaxhighlight lang="cpp" inline>typeid</syntaxhighlight> operator, if used in a context where std::type_info is not visible, is ill-informed. It is defined in header <typeinfo> (or module std).

C++26 introduces a reflection operator ^^ which returns a scalar type std::meta::info, but it is done at compile-time.[9]

The <syntaxhighlight lang="cpp" inline>typeid</syntaxhighlight> operator should not be confused for the <syntaxhighlight lang="c" inline>typeof</syntaxhighlight> and <syntaxhighlight lang="c" inline>typeof_unqual</syntaxhighlight> operators in C, or <syntaxhighlight lang="cpp" inline>decltype</syntaxhighlight> in C++, which instead are operators that expand to the type of a variable or expression at compile time.

Example

<syntaxhighlight lang="cpp"> import std;

using std::bad_typeid; using std::type_info;

class Person { public:

   virtual ~Person() = default;

};

class Employee: public Person {

   // ...

};

int main() {

   Person person;
   Employee employee;
   Person* ptr = &employee;
   Person& ref = employee;
   type_info personType = typeid(person);
   type_info employeeType = typeid(employee);
   type_info ptrType = typeid(ptr);
   type_info refType = typeid(ref);
   
   // The string returned by std::type_info::name() is implementation-defined.
   std::println("{}", personType.name()); 
   // Person (statically known at compile-time).
   std::println("{}", employeeType.name()); 
   // Employee (statically known at compile-time).
   std::println("{}", ptrType.name()); 
   // Person* (statically known at compile-time).
   std::println("{}", refType.name());
   // Employee 
   // (looked up dynamically at run-time
   // because it is the dereference of a
   // pointer to a polymorphic class).
   
   std::println("{}", typeid(ref).name());
   // Employee (references can also be polymorphic)
   Person* p = nullptr;
   
   try {
       typeid(*p); // Not undefined behavior; throws std::bad_typeid.
   } catch (const bad_typeid& e) { 
       std::println(stderr, "Exception caught: {}", e.what());
   }
   Person& ref2 = *p; // Undefined behavior: dereferencing null
   // Does not meet requirements to throw std::bad_typeid
   // because the expression for typeid is not the result
   // of applying the unary * operator.
   type_info ref2Type = typeid(ref2);

} </syntaxhighlight> Output (exact output varies by system and compiler):

Person
Employee
Person*
Employee
Employee

C++ dynamic_cast and Java cast

The <syntaxhighlight lang="cpp" inline>dynamic_cast</syntaxhighlight> operator in C++ is used for downcasting a reference or pointer to a more specific type in the class hierarchy. Unlike the <syntaxhighlight lang="cpp" inline>static_cast</syntaxhighlight>, the target of the <syntaxhighlight lang="cpp" inline>dynamic_cast</syntaxhighlight> must be a pointer or reference to class. Unlike <syntaxhighlight lang="cpp" inline>static_cast</syntaxhighlight> and C-style typecast (where type check occurs while compiling), a type safety check is performed at runtime. If the types are not compatible, an exception will be thrown (when dealing with references) or a null pointer will be returned (when dealing with pointers).

A Java typecast behaves similarly; if the object being cast is not actually an instance of the target type, and cannot be converted to one by a language-defined method, an instance of java.lang.ClassCastException will be thrown.[10]

Example

Suppose some function takes an object of type Base as its argument, and wishes to perform some additional operation if the object passed is an instance of Derived, a subclass of Base. This can be done using <syntaxhighlight lang="cpp" inline>dynamic_cast</syntaxhighlight> as follows.

<syntaxhighlight lang="cpp"> import std;

using std::array; using std::bad_cast; using std::unique_ptr;

class Foo { private:

   void specificToFoo() const {
       std::println("Method specific for Foo was invoked");
   }

public:

   // Since RTTI is included in the virtual method table there should be at
   // least one virtual function.
   virtual ~Foo() = default;

};

class Bar: public Foo { public:

   void specificToBar() const {
       std::println("Method specific for Bar was invoked");
   }

};

void qux(Foo& foo) {

   try {
       // Cast will be successful only for Bar type objects.
       Bar& bar = dynamic_cast<Bar&>(foo);
       bar.specificToBar();
   } catch (const bad_cast& e) {
       std::println(stderr, "Exception {} thrown.", e.what());
       std::println("Object is not of type Bar");
   }

}

int main(int argc, char* argv[]) {

   // Array of pointers to base class Foo.
   array<unique_ptr<Foo>, 3> foos = {
       std::make_unique<Bar>(); // Pointer to Bar object.
       std::make_unique<Bar>(); // Pointer to Bar object.
       std::make_unique<Foo>(); // Pointer to Foo object.
   }
   for (Foo f: foos) {
       qux(*f);
   }
   return 0;

} </syntaxhighlight>

Console output:

Method specific for Bar was invoked
Method specific for Bar was invoked
Exception std::bad_cast thrown.
Object is not of type Bar

A similar version of qux() can be written with pointers instead of references:

<syntaxhighlight lang="cpp"> void qux(Foo* foo) {

   Bar* bar = dynamic_cast<Bar*>(foo);
   if (derived) {
       derived->specificToBar();
   } else {
       std::println(stderr, "Object is not of type Bar");
   }

} </syntaxhighlight>

Java, C#

Java and C# both have runtime type information mechanisms.

  • In Java, the <syntaxhighlight lang="java" inline>instanceof</syntaxhighlight> checks if an object is an instance of a specific class at runtime. The C# equivalent is <syntaxhighlight lang="csharp" inline>is</syntaxhighlight>.
  • In Java, all objects inherit a getClass() method from java.lang.Object, which returns a (wildcarded) java.lang.Class<?> object representing the running instance. The C# equivalent is the GetType() method from System.Object, which returns a System.Type. In C#, generics are reified, unlike Java.
  • In Java, a class literal for a class X can be retrieved using the syntax <syntaxhighlight lang="java" inline>X.class</syntaxhighlight>, which is exactly of (non-wildcarded) type java.lang.Class<X>. The C# equivalent is the <syntaxhighlight lang="csharp" inline>typeof</syntaxhighlight> operator, which also returns System.Type, but does so at compile time, unlike Java's <syntaxhighlight lang="java" inline>X.class</syntaxhighlight>, where the class object is loaded at runtime.
  • In Java, a failed cast throws an exception of type java.lang.ClassCastException. The C# equivalent, which is thrown during a failed cast, is System.InvalidCastException, however if using <syntaxhighlight lang="csharp" inline>as</syntaxhighlight> to cast, it instead evaluates to <syntaxhighlight lang="csharp" inline>null</syntaxhighlight>.

Object Pascal, Delphi

In Object Pascal and Delphi, the operator <syntaxhighlight lang="pascal" inline>is</syntaxhighlight> is used to check the type of a class at runtime. It tests the belonging of an object to a given class, including classes of individual ancestors present in the inheritance hierarchy tree (e.g. Button1 is a TButton class that has ancestors: TWinControl → TControl → TComponent → TPersistent → TObject, where the latter is the ancestor of all classes). The operator <syntaxhighlight lang="pascal" inline>as</syntaxhighlight> is used when an object needs to be treated at run time as if it belonged to an ancestor class.

The RTTI unit is used to manipulate object type information at run time. This unit contains a set of classes that allow you to: get information about an object's class and its ancestors, properties, methods and events, change property values and call methods. The following example shows the use of the RTTI module to obtain information about the class to which an object belongs, creating it, and to call its method. The example assumes that the TSubject class has been declared in a unit named SubjectUnit.<syntaxhighlight lang="objectpascal"> uses

 RTTI, SubjectUnit;

procedure WithoutReflection; var

 MySubject: TSubject;

begin

 MySubject := TSubject.Create;
 try
   Subject.Hello;
 finally
   Subject.Free;
 end;

end;

procedure WithReflection; var

 RttiContext: TRttiContext;
 RttiType: TRttiInstanceType;
 Subject: TObject;

begin

 RttiType := RttiContext.FindType('SubjectUnit.TSubject') as TRttiInstanceType;
 Subject := RttiType.GetMethod('Create').Invoke(RttiType.MetaclassType, []).AsObject;
 try
   RttiType.GetMethod('Hello').Invoke(Subject, []);
 finally
   Subject.Free;
 end;

end; </syntaxhighlight>

See also

References

Template:Reflist

  1. ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
  2. ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
  3. ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
  4. ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
  5. ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
  6. ↑ Template:Cite book
  7. ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
  8. ↑ C++ standard (ISO/IEC14882) section 5.2.8 [expr.typeid], 18.5.1 [lib.type.info] – http://cs.nyu.edu/courses/fall11/CSCI-GA.2110-003/documents/c++2003std.pdf
  9. ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
  10. ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}