Type Identification - "typeinfo" in newer...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Type Identification A relatively new feature in C++ is type identification, where it is possible to determine the type of an object at run time. A simple example of this feature is: #include <typeinfo.h> #include <stdio.h> class A { public: virtual void f(int) {} }; class B : public A { public: virtual void f(int) {} }; int main() { A a; B b; A* ap1 = &a; A* ap2 = &b; if (typeid(*ap1) == typeid(A)) printf("ap1 is A\n"); else printf("ap1 is B\n"); if (typeid(*ap2) == typeid(A)) printf("ap2 is A\n"); else printf("ap2 is B\n"); return 0; } which produces: ap1 is A ap2 is B even though the nominal type of both *ap1 and *ap2 is A. In this example, *ap1 and *ap2 represent polymorphic types, that is, types that can refer to any class type in a hierarchy of derivations. If we omitted the virtual functions in A and B, this program would give different results, considering both *ap1 and *ap2 to be referencing A objects. typeid() produces an object of type "typeinfo", described in typeinfo.h (or just
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: "typeinfo" in newer systems). This type has operations for testing for equality, and also a member function for returning the name of a type. For example, when this code is executed: #include <typeinfo.h> #include <stdio.h> int main() { int i; double x[57]; float f1 = 0.0; const float f2 = 0.0; printf("%s\n", typeid(i).name()); printf("%s\n", typeid(x).name()); if (typeid(f1) == typeid(f2)) printf("equal\n"); return 0; } the result is: int double [57] equal Note that the typeid() comparison ignores top-level "const". The form of the name returned by name() is implementation-dependent. This feature of C++ is quite important, because it represents a partial departure from early binding, that is, fully resolving names at compile time. Sometimes it's necessary to be able to manipulate type names in a running program. A more recent language like Java(tm) has many more features of this type....
View Full Document

This note was uploaded on 02/27/2012 for the course CS 251 taught by Professor Staff during the Fall '08 term at Purdue University-West Lafayette.

Page1 / 2

Type Identification - "typeinfo" in newer...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online