Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How type casting works? 1

Status
Not open for further replies.

MahalKoCjet

Programmer
Mar 5, 2003
12
0
0
PH
Hi,
I've just read the "Complete Layman's Guide to Pointers" FAQ and i don't understand the part about type casting. Can you please give me links about type casting or please pass an article about this if you have any.

This is the code:

myThreadStruct* info = (myThreadStruct*)lp;

And I've seen another code in a different program:
CEpsApp *pApp = (CEpsApp*)AfxGetApp();
 
Well type casting has really two explanations. I will try the simple one, objects. From an Object Oriented point of view type casting is how you utilize polymorphism. If you goolge ‘polymorphism’ you should find tons of resources that might explain it better than I will. Now I’m going to use Java to simplify by eliminating pointers from the equation.

So in Java you have the base object of type “Object” and all objects derive from it even when not expressly declared

Code:
public class myclass{}
is equal to
Code:
public class myclass extends Object{}

So now if I create an instance of myclass

Code:
myclass oMyClass = new myclass();

And there is a function that takes an argument of type ‘Object’.
Code:
// signature of compare
int compare( Object obj);

I can “cast” my instance of “myclass” to type “Object” so it will match the argument type

Code:
int nResult = compare( (Object)oMyClass);

Now in C++ you have to deal with pointers verses references etc. but basically that is the fundamental gist of “casting” and the pointers part of it is more about understanding what a pointer is in C++.

Hope that helps
-pete

 
The simple type casting is nothing more than supressing of compiler error messages like "Argumet type mismatch". Type cast, for example, is applicable when you want to use the same memory location for different purposes. Say, if you want to look to internal structure of doubles, you can cast:
double rr=123.;
long *lptr=(long *)&rr;
In C++ there are more sophisticated cast operators like static_cast and dynamic_cast, which are used for casting between interfaces in classes derived from several interface clases, but I still cannot imagine surely how do they work internally.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top