Monday, May 24, 2010

Why would you use reinterpret_cast in c++?

I think it's used to convert a pointer of one type to another by performing a "binary copy". What does that mean and why would you ever want to do that?

Why would you use reinterpret_cast in c++?
The reinterpret cast converts one pointer type to another. It does not perform a binary copy of the object.





Its best use is to convert a base pointer to a class back to the derived class type. for example:





class A


{


};





class B: public A


{


public:


int m_nVar;


};





// base pointer pointing to derived class


// has no access to m_nVar


A *aPtr = new B;





// cast base pointer back to derived class pointer


// has access to m_nVar


B *bPtr = reinterpret_cast%26lt;B%26gt;(aPtr);





You can also use it to cast char* to int*, or any other number of unsafe converstions, but this is not recommended.


No comments:

Post a Comment