Templates Namespaces Exception Handling Rtti
Templates Namespaces Exception Handling Rtti
Templates
Namespaces
Exception handling
RTTI
Templates
&
Namespaces
Objectives of this
Session
• Templates
– Identify need of Templates
– Describe function Templates & class Templates
– Distinguish between templates & macros
• Namespaces
– Identify need of namespaces
– State rules for using namespaces
Need of Templates
void swap(int &a,int &b) void swap (char &ch1,char &ch2)
{ int temp; { char temp;
temp = a; temp = ch1;
a=b; ch1 = ch2;
b = temp; ch2 = temp;
} }
• Syntax
cast_name<type>(expression);
casting Operators :
const_cast
• casts away the constness of its expression
• e.g. const_cast
char *string_copy(char *);
const char *pc_str;
char *pc = string_copy (const_cast<char*>(pc_str));
casting Operators :
static_cast
• Any conversions which compiler performs implicitly can be
made explicit using static_cast
• Warning messages for loss of precision will be turned off.
• reader, programmer and compiler all are made aware of fact
of loss of precision.
• e.g. static_cast
double dval;
int ival;
ival += dval; // unnecessary promotion of ival to
// double can be eliminated by using
// explicit casting
ival += static_cast<int>(dval);
casting Operators :
reinterpret_cast
• Complex <double> *pcom;
• Char *pc = reinterpret_cast < char*>(pcom)
• Most dangerous
Example
#include <iostream>
using namespace std;
int main()
{
int i;
char *p = "This is a string";
i = reinterpret_cast<int> (p); // cast pointer to integer
cout << i;
return 0;
}
casting Operators :
dynamic_cast
• dynamic_cast operators are used to obtain pointer to the
derived class
void company :: payroll (employee *person)
{
manager *pm = dynamic_cast<manager*>(person);
// if person at runtime refers to manager class, then dynamic
cast is successful
if(pm)
// use pm to call bonus using pm -> bonus;
else
// use employee’s member function
}
Example