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 "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.
India seo freelance web designer India web development ecommerce website developer India
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100