C++ Interview Questions,C++ Questions,C++ Papers
Thursday, September 4, 2014
C++ Resources
Monday, May 28, 2012
Convert int to string in C++
string int2str (int n) {
stringstream ss;
ss << n;
return ss.str();
}
How to convert string to integer in C++
int str2int (const string &str) {
stringstream ss(str);
int n;
ss >> n;
return n;
}
Thursday, July 1, 2010
More job interview questions
Job Interview Questions : More than 10000 job interview questions with solution to prepare for your job interview
Interview Questions
Thursday, February 4, 2010
What is RTTI in C++ ?
Runtime Type Information (RTTI) is the concept of determining the type of any variable during execution (runtime.) The RTTI mechanism contains:
- The operator dynamic_cast
- The operator typeid
- The struct type_info
The dynamic_cast can only be used with pointers and references to objects. It makes sure that the result of the type conversion is valid and complete object of the requested class.
// dynamic_cast
#include
#include
using namespace std;
class Base_Class { virtual void dummy() {} };
class Derived_Class: public Base_Class { int a; };
int main () {
try {
Base_Class * ptr_a = new Derived_Class;
Base_Class * ptr_b = new Base_Class;
Derived_Class * ptr_c;
ptr_c = dynamic_cast< Derived_Class* >(ptr_a);
if (ptr_c ==0) cout << "Null pointer on first type-cast" << endl;
ptr_c = dynamic_cast< Derived_Class* >(ptr_b);
if (ptr_c ==0) cout << "Null pointer on second type-cast" << endl;
} catch (exception& my_ex) {cout << "Exception: " << my_ex.what();}
return 0;
}
There are two dynamic_casts from pointer objects of type Base_Class* (namely ptr_a and ptr_b) to a pointer object of type Derived_Class*.
If everything goes well then the first one should be successful and the second one will fail. The pointers ptr_a and ptr_b are both of the type Base_Class. The pointer ptr_a points to an object of the type Derived_Class. The pointer ptr_b points to an object of the type Base_Class. So when the dynamic type cast is performed then ptr_a is pointing to a full object of class Derived_Class, but the pointer ptr_b points to an object of class Base_Class. This object is an incomplete object of class Derived_Class; thus this cast will fail!
bad_cast exception is being thrown in case of conversion fail.
Typeid return an structure of type_info . You can get the detail and type of the object at run time.
int * a;
int b;
a=0; b=0;
if (typeid(a) != typeid(b))
{
cout << "a and b are of different types:\n";
cout << "a is: " << typeid(a).name() << '\n';
cout << "b is: " << typeid(b).name() << '\n';
}
C++ Resources and Interview Questions
Free C++ Books
Free C Books
C++ Interview Questions
C++ Questions
Interview Questions