Casting in c++

In c++ there are 4 types of casting

1. static_cast
2. const_cast
3. dynamic_cast
4. reinterpret cast

1. static cast
1. It is most general purpose cast in c++
2. It is able to cast basic type of casting i.e. int to double, base class pointer to derive class pointer
3. It can not used to remove constantness or volatileness in object.
4. It cannot be used to cast struct to int or a duble into a pointer.

    int x;
    double d;
   d = static_cast<double>(x);


2. Const_cast

1. This type of casting is used to remove constatness or volatileness.
2. const_cast rejects if request to modify other then constantness or volatileness.


#include <iostream>
using namespace std;
class student
{
private:
    int roll;
public:
    // constructor
    student(int r):roll(r) {}
     // A const function that changes roll with the help of const_cast
    void fun() const
    {
        ( const_cast <student*> (this) )->roll = 5;
    }
    int getRoll()  { return roll; }
};
int main(void)
{
    student s(3);
    cout << "Old roll number: " << s.getRoll() << endl;
    s.fun();
    cout << "New roll number: " << s.getRoll() << endl;
    return 0;
}

3. dynamic_cast
1. Used to perform safe cast down to across an inheritance hierarchy.
2. used to cast pointer or reference of base class object into pointer reference to derived or sibling base class object.
3. fail if no inheritance involved or try to remove constantness.
4. If dynamic_cast fails return null when pointer or throw exception when reference.
5. mechanism that exposes information about an object’s data type at run time and is available only for the classes which have at least one virtual function. It allows the type of an object to be determined during program execution

#include<iostream>
using namespace std;
class B { virtual void fun() {} };
class D: public B { };

int main()
{
B *b = new D;
D *d = dynamic_cast<D*>(b);
if(d != NULL)
cout << "works";
else
cout << "cannot cast B* to D*";
getchar();
return 0;
}


4. reinterpret cast
1. Most risky casting in c++.
2. Doesn't check feasibility; it is the responsibility of developer about the behaviors.
3. used to cast any type.
4. The most common use of the reinterpret cast is to cast between function pointer type.

Ex:
 #include <iostream>  
using namespace std;  
  
// Returns a hash code based on an address  
unsigned short Hash( void *p ) {  
   unsigned int val = reinterpret_cast<unsigned int>( p );  
   return ( unsigned short )( val ^ (val >> 16));  
}    
using namespace std;  
int main() {  
   int a[20];  
   for ( int i = 0; i < 20; i++ )  
      cout << Hash( a + i ) << endl;  
}    
Output:   
64641  

Comments

Popular posts from this blog

STL Questions

Producer Consumer problem using mutex

Interview questions