Click here to Skip to main content
Click here to Skip to main content

Casting Basics - Use C++ casts in your VC++.NET programs

By , 23 Aug 2002
 

Prologue

If someone were to ask me to name the single most exciting feature of C++, I'd reply saying that it was the ability to perform casts from one type to another. Of course this is purely a whimsical and highly irrational love I have for casts and is not a reflection of any great technical pondering I might have committed on casts and their usefulness. I mentally squeal with delight every time I see code that looks something similar to ((CNishApp*)AfxGetApp())->CustomFunc() or (LPSTR)(LPCTSTR)m_str. This was all quite well when I was using VC++ 6 but when I started moving some of my old applications to VC++.NET, it was a little disconcerting to see all those compiler warnings about how my C style casts were now deprecated.

That's when I took a look at the new C++ casting operators that were available and quickly discovered that, they were a much safer and smarter way for doing casts. This article will run through the various casting operators that are available and will suggest when and where you might want to use each of these casting operators. The entire article has been written from a managed extensions context and therefore I only discuss managed classes in this article. This has some interesting corollaries which I mention later in the article.

Dangers of C-style casts

The single biggest problem with C-style casts is that they are absolutely and totally unsafe. No compile time or run time checks are made and you are left with full freedom to dig your own grave, as deep as you want to. There is nothing to stop you from casting a base class pointer that points to a base class object to a derived class pointer, which means that when you make your derived class method calls, catastrophe results most assuredly.

Another problem is that you never know what kind of cast you are trying to achieve. All casts you can do look the same as far as syntax goes. Obviously this can be a pain in the neck when you are debugging. In addition some people use the functional style casts where they do int(x) instead of (int)x and this results in further obfuscation of the code, because C/C++ code is just about always sprinkled with functions and their accompanying brackets.

The C++ casting operators

There are five casting operators provided which serve to replace the old C-style casts. Each has a specific purpose and intended usage which I explain later down the article. Before that I'd like to touch on the subject of polymorphic classes. Any class that has virtual functions is a polymorphic class. Now this marks a major distinction among classes in the old unmanaged world. But in the new managed world of C++ coding, every class is polymorphic, because all managed classes derive implicitly from System::Object which has virtual methods of its own. Thus this renders every __gc class as a polymorphic class. This allows us to exclusively use the safer dynamic_cast instead of static_cast just about everywhere, which was not possible in unmanaged C++.

  • static_cast
  • dynamic_cast
  • const_cast
  • reinterpret_cast
  • __try_cast (managed extensions only)

static_cast

The static_cast operator relies only on compile time information. Run time checks are not done to ensure a safe cast. You can do both downcasts and upcasts using static_cast, but there are dangers involved  which I demonstrate later down the article. The syntax for using the static_cast operator is shown below :-

T t = static_cast<T>(expression);

An example usage would be something like :-

CMainFrame* pMF = static_cast<CMainFrame*>(AfxGetMainWnd());

dynamic_cast

The dynamic_cast operator relies both on compile time and run time information. When you attempt to do a cast using the dynamic_cast operator, a run time check is made to see if this is a safe cast, and if the cast is unsafe then this the cast returns NULL. Thus by checking for NULL, we can determine whether the cast attempt was successful or not. The syntax is :-

T t = dynamic_cast<T>(expression);

A sample usage of dynamic_cast would be like :-

void Hello(Base* p1)
{
    //...
    Child *c1 = dynamic_cast<Child*>(p1);
    if(c1)
    {
        // we can safely use c1
    }
    //...
}

const_cast

The const_cast operator is used to remove the const, volatile, and __unaligned attributes) from a class. __unaligned is a Microsoft extension to C++ and I am not quite sure of what it's purpose is. You can use const_cast only to cast between types that differ only in their const-ness or volatility. The syntax for use is similar to the other casts :-

T t = const_cast<T>(expression);

A sample use would be something similar to :-

void Abc(const Base* pB)
{
    //...
    Xyz(const_cast<Base*>(pB));
}

void Xyz(Base* pB)
{
    //...
}

reinterpret_cast

To be really honest I have no clue why they have this one because as far as I see it, its just as bad as the old C style casts except that it advertises it's lack of safety quite explicitly. You can use the reinterpret_cast operator to convert from one type to any other type. It's syntax is :-

T t = reinterpret_cast<T>(expression);

Basically the only safe place to use it would be where we cast from Type-1 to Type-2 and later we cast back Type-2 to Type-1. Now we have the exact object back as when we started this reinterpret_cast business.

/* A and B are unrelated types */
A *a = reinterpret_cast<A*>(new B());
B *b = reinterpret_cast<B*>(a); //safe to use b

__try_cast

__try_cast is a managed extension keyword not available in unmanaged C++. It's essentially similar to dynamic_cast except that it throws an exception on failure whereas dynamic_cast returns NULL. The syntax is :-

T t = __try_cast<T>(expression);

The exception that gets thrown is System::InvalidCastException and you better use a try-catch block if you are using __try_cast unless you want to see your program break in between, though that might actually be a good thing when you are still developing it. A sample use is shown below :-

try
{
    p2 = __try_cast<Base*>(p1);
    //use p2 safely now
    //...
}
catch(System::InvalidCastException*)
{
    Console::WriteLine("blast!");
}

When to use and what?

Well, we've seen 5 different casting operators and they are supposed to be replacements for the old C-style casts. It might be a little baffling to choose the correct cast operator when you are coding. To be really honest, till recently I had no clue when to use what! Anyway I have created certain imaginary casting scenarios and used each of the cast operators to try and do the casts [where permitted by the compiler] and I have made an attempt to demonstrate when and why some cast operators are not suitable and when they are suitable. Of course the recommendations are strictly my own and I do not claim that they might be the most suitable options, but then I intend to keep updating the article with valuable input from C++ gurus who happen to come across this article.

Test classes

These are the test classes and enums that I have used in my experiments.

/*
Our test base class
*/
__gc class Base
{
public:
    int dummy;
};

/*
Our test derived class
*/
__gc class Child : public Base
{
public:
    char anotherdummy;
};

/*
An independent test class
*/
__gc class Base2
{
};

enum CastType
{
    tdynamic_cast,
    tstatic_cast,
    tconst_cast,
    treinterpret_cast,
    ttry_cast 
};

Downcasting

Downcasting is when you convert from a base class pointer to a derived class pointer. I have written a function called BaseToChild which does various kinds of downcasting based on the CastType enumeration parameter passed to it. Obviously I cannot use const_cast here because we are casting across unlike types.

Child* BaseToChild(Base* p,CastType casttype)
{
    Child* retptr = NULL;
    switch(casttype)
    {
    case tdynamic_cast: 
        retptr = dynamic_cast<Child*>(p);
        break;
    case tstatic_cast:
        retptr = static_cast<Child*>(p);
        break;
    case tconst_cast:
        /* This won't compile */
        //retptr = const_cast<Child*>(p);
        break;
    case treinterpret_cast:
        retptr = reinterpret_cast<Child*>(p);
        break;
    case ttry_cast:
        try
        {
            retptr = __try_cast<Child*>(p);
        }
        catch(System::InvalidCastException*)
        {
            //...
        } 
        break; 
    }
    return retptr;
}

Unsafe downcasting

Base *pBase1 = new Base();
Child *pChild1 = NULL;

I have pBase1 which holds a Base object and I am now going to attempt to downcast it to a Child object. Obviously this is unsafe and something which I really shouldn't be doing. I called BaseToChild four times, once for each type of cast (const_cast not usable here).

//dynamic_cast
pChild1 = BaseToChild(pBase1,tdynamic_cast); 
if(!pChild1)
{
    Console::WriteLine("dynamic_cast - downcast failure");
}
else
{
    Console::WriteLine("dynamic_cast - downcast success");
}

I only show the sample code for dynamic_cast, but the code for the other three casts are very much similar. I summarize my results in the table below.

Cast Result Notes
dynamic_cast Failure Fails and returns NULL
static_cast Success Unsafe cast made
reinterpret_cast Success Unsafe cast made
__try_cast Failure Fails and throws an exception

Safe downcasting

Base *pBase1 = new Child();
Child *pChild1 = NULL;

Alright now we have the Base object holding a Child object. Now it's perfectly safe to downcast to the derived class. Again I called BaseToChild four times, once for each type of cast except const_cast. The table below shows the results I got.

Cast Result Notes
dynamic_cast Success Safe cast
static_cast Success Safe cast
reinterpret_cast Success Safe cast
__try_cast Success Safe cast

Recommendation for downcasting

If you are absolutely sure that the cast is going to be safe, you can use any of the four cast operators above, but I'd suggest that you use static_cast because that'd be the most efficient way of casting. If you are even a microscopic percentage unsure as to the safety of your cast, you must simply *avoid* static_cast and reinterpret_cast both of which are quite dangerous here. You may use either dynamic_cast or __try_cast depending on whether you like to check for NULL or you like to have an exception raised and handled.

Upcasting

Upcasting is when you cast from a derived class to one of the parent classes in the inheritance chain. Usually upcasting is pretty much safe except in certain rare situations that are actually a result of bad coding rather than anything else. I demonstrate both scenarios below. Just like I had a function for downcasting, I also have one for upcasting called ChildToBase. Just as previously, I cannot use const_cast here because we are casting across unlike types.

Base* ChildToBase(Child* p,CastType casttype)
{
    Base* retptr = NULL;
    switch(casttype)
    {
    case tdynamic_cast:
        retptr = dynamic_cast<Base*>(p);
        break;
    case tstatic_cast:
        retptr = static_cast<Base*>(p);
        break;
    case tconst_cast:
        /* This won't compile */
        //retptr = const_cast<Base*>(p);
        break;
    case treinterpret_cast:
        retptr = reinterpret_cast<Base*>(p);
        break;
    case ttry_cast:
        try
        {
            retptr = __try_cast<Base*>(p);
        }
        catch(System::InvalidCastException*)
        {
            //...
        }
        break; 
    }
    return retptr;
}

Safe upcasting

Base *pBase2 = NULL;
Child *pChild2 = new Child();

I am casting from Child* to Base* which is perfectly okay and safe. I show below the results I got for each cast operator.

Cast Result Notes
dynamic_cast Success Safe cast
static_cast Success Safe cast
reinterpret_cast Success Safe cast
__try_cast Success Safe cast

Unsafe upcasting

Base *pBase2 = NULL;
/* Intentionally create a bad pointer */
Child *pChild2 = reinterpret_cast<Child*>(new Base2()); 

Here I have intentionally created a Base2 object and cast it to a Child object using reinterpret_cast. This is a totally unsafe cast, but I have done this to demonstrate what happens when you do an unsafe upcast. I show my results in the table below :-

Cast Result Notes
dynamic_cast Failure Fails and returns NULL
static_cast Success Unsafe cast made
reinterpret_cast Success Unsafe cast made
__try_cast Failure Fails and throws an exception

Recommendations for upcasting

In most situations upcasting should be quite safe except when you have a bad derived class pointer (bad in the sense that it points to the wrong object). Therefore my recommendation for upcasting is to use static_cast which should be the most efficient. If your upcasts are unsafe it's probably time for you to sit down and figure out what's going wrong in your code rather than using dynamic_cast or __try_cast. In addition keep in kind that upcasting would probably be implicitly done in most situations.

const_cast usage

Consider the code below :-

const Base *pB = new Base();
/* won't compile */
pB->dummy = 100;

You'll get a compiler error, because you are trying to modify a const object. Using const_cast, you can quickly overcome this problematic situation.

const_cast<Base*>(pB)->dummy = 100;
/* should show 100 on the console */
Console::WriteLine(pB->dummy);

Another useful application of const_cast comes in const member functions. When you mark a class member as const, you are telling the compiler that this function is a read-only function that will not modify the object. This means your this pointer is now a const Class * const instead of just Class * const. Now suppose that for some reason you want to modify some member from this member function. You can use const_cast as shown below. Of course you might also want to rethink your design if you are having to un-const all your const member functions.

void A::abc() const
{
    const_cast<A* const>(this)->m_total++; 
}

reinterpret_cast usage

As I already mentioned earlier, this is the most unsafe of all the C++ cast operators and it's probably best to avoid using it. But then when porting old code, you might want to convert the old style casts to reinterpret_cast. In my example, Base2 and Base are two managed classes that do not share an inheritance chain except for deriving automatically from System::Object. Assume that for whatever reason, we need to cast a Base2 object into a Base object and later cast it back to a Base2 object.

Base *pB1 = NULL;
Base2 *pB2 = new Base2();

Let's first try to use dynamic_cast :-

/* Compiles, but fails */
pB1 = dynamic_cast<Base*>(pB2);
if(!pB1)
    Console::WriteLine("dynamic_cast failed");

It compiles fine, but fails during run-time. Now let's try using static_cast :-

/* Won't compile */
//pB1 = static_cast<Base*>(pB2);

Okay, great! That won't even compile because the compile-time check fails. How about __try_cast :-

/* Compiles, but throws exception */
try
{
    pB1 = __try_cast<Base*>(pB2);
}
catch(System::InvalidCastException*)
{
    Console::WriteLine("__try_cast has thrown an exception");
}

Just like dynamic_cast this compiles fine too, but throws an exception at run-time. That leaves us just reinterpret_cast now.

/* This is a sort of blind man's cast */
pB1 = reinterpret_cast<Base*>(pB2);

Oh boy! That compiled and also ran fine. No errors. pB1 which was declared as a Base object now holds a Base2 object. To test this, we can try to re-cast it back using dynamic_cast.

/* Now we cast it back */
Base2* pDest = dynamic_cast<Base2*>(pB1);
if(pDest)
{
    Console::WriteLine("Original pointer has been obtained");
}

Well, as you might have understood by now, it's safest to avoid using reinterpret_cast, but it does have it's uses and without it, we'd still have had to use C-style casts when porting old code.

Conclusion

Well, the magic of casts haven't died yet, and casts live through the C++ cast operators and continue to enthrall C/C++ lovers all over the world. I am not sure that everything I have suggested in the article is nice and proper. But I trust that I'll get the required critical feedback to correct any erroneous statements and recommendations I might have made.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Nish Sivakumar

United States United States
Nish is a real nice guy who has been writing code since 1990 when he first got his hands on an 8088 with 640 KB RAM. Originally from sunny Trivandrum in India, he has been living in various places over the past few years and often thinks it’s time he settled down somewhere.
 
Nish has been a Microsoft Visual C++ MVP since October, 2002 - awfully nice of Microsoft, he thinks. He maintains an MVP tips and tricks web site - www.voidnish.com where you can find a consolidated list of his articles, writings and ideas on VC++, MFC, .NET and C++/CLI. Oh, and you might want to check out his blog on C++/CLI, MFC, .NET and a lot of other stuff - blog.voidnish.com.
 
Nish loves reading Science Fiction, P G Wodehouse and Agatha Christie, and also fancies himself to be a decent writer of sorts. He has authored a romantic comedy Summer Love and Some more Cricket as well as a programming book – Extending MFC applications with the .NET Framework.
 
Nish's latest book C++/CLI in Action published by Manning Publications is now available for purchase. You can read more about the book on his blog.
 
Despite his wife's attempts to get him into cooking, his best effort so far has been a badly done omelette. Some day, he hopes to be a good cook, and to cook a tasty dinner for his wife.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Generalreinterpret_cast and a real-world use for it. [modified]memberleeor_net11-Jan-10 23:11 
I hate it when people say they can never find a use for reinterpret_cast or that they don't know why it's there. The very simple explanation is that it's there to support legacy code and C/C++ interoperability (this coming from Bjorn himself). Well designed C++ programs should almost never need to reinterpret a pointer type. Actually, I can comfortably say that user-mode programs written in C++ should never need to use reinterpret_cast.
 
Back to my point, I'm developing software now that makes use of two well known libraries both written in C: Lua and libcurl. The issue comes when building wrapper classes in C++ around these libraries. Sometimes you need to provide non-static member data to these libraries and the only way to do so effectively is to reinterpret_cast void pointers, particularly when providing callback functions which generally need to be defined as static member functions.
 
Following is an example of using libcurl within a class. This class is very much stripped down for simplicity and to illustrate my point:
 
 
class Downloader
{
public:
	Downloader() : mProgress(0.0)
	{}
 
	double getProgress() const
	{
		return mProgress;
	}
 
private:
	static int progress(void *ptr, double dlTotalSize, double dlCurrentSize, double ul, double ut)
	{
		float *progressFloat = reinterpret_cast<double*>(ptr);
 
		if (dlTotalSize > 0.0)
			*progressFloat = dlCurrentSize / dlTotalSize;
		return 0;
	}
 
	double mProgress;
};
 
Now without going into the details of how to work with libcurl itself and ignoring the fact that this class is utterly useless in its present form in a real-world application, suffice it to say that the function progress() is used as a callback function and its prototype is defined by libcurl (C/C++ interoperability). Because it's static we can't use non-static class members. Granted I could just define mProgrss as static because it's a POD but what if I wanted to pass a pointer to a non-POD data type? I wouldn't be able to do it. This is exactly why reinterpret_cast is provided.
QuestionHow did you know that it's unsafe?memberAkram Ben Hassan10-Oct-06 12:00 
Sorry for the hard title your article is awsome Smile | :)
I just wanna ask about the unsafety you mentioned many times (such as in the tables following the codes testing your ChildToBase And BaseToChild Functions)
 
How did you make sure about the unsafe cases that they are unsafe?
Many thanks and nice work
Questionstatic_cast and multiple inheritance?memberIoan Bizau10-Jul-06 11:44 
I see you didn't mention anything regarding that issue...
 
http://ib.stalker.ro
GeneralCompiler Warning C4312memberNguyen Phuoc Dai23-Dec-05 17:32 
I have loaded a class for menu from a link in CButtonST article of Davide Calabro. The code were writen and tested on VC++ 6.0. Because new my project were developed on VC++.NET using managed C++, so when I add the menu class into my project, the compiler display "warnings C4312: 'type cast' : conversion from 'UINT' to 'HMENU' of greater size" at the code lines that cast UINT to HMENU as following:
 
....
m_SubMenus.Add((HMENU)(nID));
...
 
The parameter type of Add(...) function was HMENU. I have used all new casting methods that you have described, but the problem was not solved.
Do you have any suggestions?
Thanks.
GeneralRe: Compiler Warning C4312memberleeor_net28-Aug-11 14:16 
You are misunderstanding your compiler's error message. Your problem is totally unrelated to this article.
Generalreinterpret_cast isn't a drop-in replacement for a C-style castmemberDon Clugston10-Nov-04 12:35 
reinterpret_cast is actually a lot safer than a C-style cast. Using it will pick up a lot of errors in your code.
 
(a) You can't cast away 'const' in a reinterpret_cast. Only const_cast can do that.
 
(b) There are limits as to what what reinterpret_cast can convert between. Interestingly, there a few things that static_cast can do that reinterpret_cast can't. (I believe that reinterpret_cast can't do downcasts, for example - I don't think it can change the binary representation of what it's pointing to, whereas a static_cast can adjust 'this' pointers).
 
In the worst case, a C-style cast may need to be changed to a triple combo of reinterpret_cast, static_cast and const cast!
 
One problem I find is that purely by habit, a lot of C-style casts remain in my code, and it's virtually impossible to find them by a text-editor search. The Digital Mars C++ compiler (free download from www.digitalmars.com) has a command-line option to generate a warning whenever it finds a C-style cast. I thoroughly recommend it.
 
In my 'Member Function Pointers' article,
I define two other casts:'implicit_cast', the safest of all possible casts, it succeeds only if there is an implicit conversion between the types (eg, from long to int),
and 'horrible_cast' (also called 'union_cast' by others) which simply reinterprets bits. (ie, it does what you would guess reinterpret_cast does, with no restrictions). Very, very evil.
 
http://www.codeproject.com/cpp/FastDelegate.asp
 
//		implicit_cast< >
// I believe this was originally going to be in the C++ standard but 
// was left out by accident. It's even milder than static_cast.
// I use it instead of static_cast<> to emphasize that I'm not doing
// anything nasty. 
// Usage is identical to static_cast<>
template <class OutputClass, class InputClass>
inline OutputClass implicit_cast(InputClass input){
	return input;
}

GeneralNice Job NisheditorNick Parker3-May-03 9:25 
Another nice job Nish, what's next anyway?
 
-Nick Parker
Generalbeware of dynamic_cast<>memberSwinefeaster28-Oct-02 10:29 
Just want to point out that I've had some serious issues with using dynamic_cast<> on invalid pointers. Instead of just failing and returning NULL, this actually corrupt memory! What I had to do was make up a hash table of valid object pointers and always look up the pointer before trying to do a dynamic_cast<>, and even then wrap the call in a try-catch block. The docs are all lies! Either that, or MS really buggered up their implementation of that cast.
 
swine
 
Check out Aephid Photokeeper, the powerful digital
photo album solution at www.aephid.com.

GeneralRe: beware of dynamic_castsussSuneet Chandok25-Aug-05 19:02 
I faced the same problem.
Here's the solution.
 
1) Either opt for 1 BYTE structure padding in VC options.
 
OR
 
2) Add pragma code to avoid padding.
 
#pragma pack(push,1)
struct someStruct
{
};
#pragma pop(push)
 
Regards
SChandok
Generalcast from unsigned char tosussAnonymous24-Oct-02 4:24 
hello
 
example:
unsigned char test[50];
 
how can i cast test to unsigned char __gc[]

GeneralRe: cast from unsigned char toeditorNishant S24-Oct-02 5:24 
unsigned char test[50];
strcpy((char*)test"hello world");
unsigned char mantest __gc[] = 
    new unsigned char __gc[strlen((char*)test)];
for(int i=0; i<mantest->Length; i++)
    mantest[i] = test[i];
 
Nish
 

Author of the romantic comedy

Summer Love and Some more Cricket [New Win]

Review by Shog9
Click here for review[NW]

GeneralRe: cast from unsigned char tomemberleeor_net28-Aug-11 14:18 
You're using C++, right?
 
Why are you using raw character arrays? Sse std::string's or boost strings instead.
General__unalignedmemberW2k20-Sep-02 11:16 

For those who like me wonder what the heck __unaligned is: It's a Microsoft extension to the C++ language that does .. absolutely nothing. It's "reserved for future implementations".
 
See the chapter "Microsoft Extensions (C++)" in MSDN.
 
[ PlanetCPP ][ home of the n00blist ]
GeneralRe: __unalignededitorNishant S20-Sep-02 14:07 
Thanks Smile | :)
 
Nish
 

Author of the romantic comedy

Summer Love and Some more Cricket [New Win]

Review by Shog9
Click here for review[NW]

GeneralRe: __unalignedmemberTim Smith8-Oct-02 15:18 
__unaligned does A LOT and is not "reserved for future implementations". The problem is, that for your x86 processors, there is no need since it doesn't have alignment faults. However, on processors such as the Alpha or many of your Windows CE computers, this tells the compiler to generate slower, but fault safe code.
 
Tim Smith
 
"Programmers are always surrounded by complexity; we can not avoid it... If our basic tool, the language in which we design and code our programs, is also complicated, the language itself becomes part of the problem rather that part of the solution."
Hoare - 1980 ACM Turing Award Lecture
GeneralRe: __unalignedmemberTim Smith8-Oct-02 15:26 
FYI:
 
Many operating systems will trap alignment faults and then perform corrective actions and eat the fault. However, this can beIS VERY expensive. Much cheaper to use __unaligned and not even get the OS's fault code involved.
 
Tim Smith
 
"Programmers are always surrounded by complexity; we can not avoid it... If our basic tool, the language in which we design and code our programs, is also complicated, the language itself becomes part of the problem rather that part of the solution."
Hoare - 1980 ACM Turing Award Lecture
GeneralRe: __unalignedmemberW2k11-Oct-02 5:56 
So you say, and while I have no reason to doubt this, MSDN does not agree with you:
 
The list of Microsoft Extensions to the C++ language in VC++.NET clearly lists __unaligned as "reserved for future implementations". The corresponding page for VC++ 6.0 does, too. __unaligned is also not found in this list of C++ keywords (in VS.NET). It does, however, say that names with two leading underscores (__) are reserved for compiler implentations. Hence, it's not something we mortals need to bother with learning about, anyway Poke tongue | ;-P
 
[ PlanetCPP ][ home of the n00blist ]
Generalreinterpret_castmemberNorm Almond3-Sep-02 8:51 
One good example
 
LRESULT CMyWnd::OnMyOwnMessage(WPARAM wParam, LPARAM lParam)
{
CMyNotificationObject* pObject = reinterpret_cast(LPARAM);
 
return 0;
}
 
My 2 bitz worth...
 
Normski. - the next bit of code is self modifying ... jmp 0xCODE
GeneralRe: reinterpret_casteditorNishant S17-Sep-02 15:08 
Thanks Normski Smile | :)
 
Regards,
Nish
 

Author of the romantic comedy

Summer Love and Some more Cricket [New Win]

Review by Shog9
Click here for review[NW]

GeneralRe: reinterpret_castmemberSantosh M. P.19-Sep-02 20:40 
Agreed that this cast is not at all safe. But like the situation mentioned by Normski there could be other situations as well. So instead of using the C style cast using reinterpret_cast will help solve a lot of debugging headache. Imaging a codebase having millions of lines of code and a bug related to casting occurs. It would be very difficult to locate the bug if C style cast is used. In the case of reinterpret_cast, at least, this word "reinterpret_cast" can be searched for and that part of the code can be debugged.
 
« Superman »
GeneralRe: reinterpret_casteditorNishant S20-Sep-02 14:08 
Santosh M. P. wrote:
this word "reinterpret_cast" can be searched for and that part of the code can be debugged.
 
Cool! That's a very good point Smile | :)
 
Regards,
Nish
 

Author of the romantic comedy

Summer Love and Some more Cricket [New Win]

Review by Shog9
Click here for review[NW]

GeneralRe: reinterpret_castmemberJudexOmnium17-Feb-04 11:16 
reinterpret_cast is a great tool for casting from pointers to non-pointers, and back again.   for example, casting between HWND and long datatypes.   Another great example is when you are using the Interlocked functions (e.g. InterlockedIncrement).   InterlockedIncrement expects a long*.   The code below illustrates a class which expects to be used by multiple asynchronous methods.
 
class CRefCountedClass
{
   long m_RefCount;
 
   long AddRef()
   {
         // Thread-safe reference count increment.
         InterlockedIncrement(reinterpret_cast<long*>(&m_RefCount));
         return m_RefCount;
   }
 
   // ... Additional implementation
};
Questionhelp ?memberimran_rafique27-Aug-02 22:30 
when i get process main window hwnd from its property
and i type cast it into hwnd using
hwnd=(HWND)intptr.ToInt32();
but it does not work properly because when i use Getwindow
to get its child window it return null i dont now why becuse it have child hwnd.

 
r00d0034@yahoo.com
AnswerRe: help ?editorNishant S17-Sep-02 15:07 
That's a coding issue imran and not a casting issue. Ask in the concerned forums and someone might help you.
 
regards,
Nish
 

Author of the romantic comedy

Summer Love and Some more Cricket [New Win]

Review by Shog9
Click here for review[NW]

GeneralCasting in JavaScriptmemberAlexpro25-Aug-02 21:50 
You say that C++ is so beautiful because you can cast. You should try JavaScript and there you can cast a string into a 2D matrix of doubles. How about that? Smile | :) Smile | :)
 
Best regards,
Alexandru Savescu
GeneralRe: Casting in JavaScriptmemberBehind The Scene31-Dec-06 3:57 
That is not casting… The JavaScirpt engine is interpreting the string.
 
ROFLOLMFAO

General__try_castmemberJörgen Sigvardsson25-Aug-02 6:12 
The syntax example for __try_cast shows dynamic_cast.
 
All in all: Very nice article!
 
Preferred storyline:
- I am your father. Search your feelings and you'll know it's the truth. Together we can rule this galaxy like father and son.
- Ok dad. Let's kick some butt!
GeneralRe: __try_casteditorNishant S25-Aug-02 15:50 
Jörgen Sigvardsson wrote:
The syntax example for __try_cast shows dynamic_cast.
 
Blush | :O Blush | :O Blush | :O
 

Jörgen Sigvardsson wrote:
All in all: Very nice article!
 
Thanks Jorgen Smile | :)
 
Nish
 

Author of the romantic comedy

Summer Love and Some more Cricket [New Win]

Review by Shog9
Click here for review[NW]

GeneralRe: __try_casteditorNishant S25-Aug-02 16:03 
Jörgen Sigvardsson wrote:
The syntax example for __try_cast shows dynamic_cast.
 
Whew! That's fixed now. Thanks again Jorgen!
 
Nish Smile | :)
 

Author of the romantic comedy

Summer Love and Some more Cricket [New Win]

Review by Shog9
Click here for review[NW]

Generalold unmanaged world?? HahahamemberRodrigo Strauss24-Aug-02 19:40 
old unmanaged world??? The marketing guys from Microsoft are doing a very good job. Wink | ;)
 
Rodrigo Strauss
General+1 astutememberChris Losinger25-Aug-02 6:26 
Smile | :)
 

Though the cough, hough and hiccough so unsought would plough me through,
enough that I o'er life's dark lough my thorough course pursue.
--Stuart Kidd

GeneralRe: +1 astuteeditorNishant S25-Aug-02 15:55 
Uhmmm, you unmanaged programmers do stick together eh? Wink | ;-)
 
Nish
 
p.s. In your case I understand your feelings for the new compiler [after reading your static lib size tragedy in the MS forums], but that's more a compiler issue rather than a managed-unmanaged issue I guess.
 

Author of the romantic comedy

Summer Love and Some more Cricket [New Win]

Review by Shog9
Click here for review[NW]

GeneralRe: old unmanaged world?? HahahaeditorNishant S25-Aug-02 15:52 
Er, by old I didn’t mean “old and shriveled”, I just meant old as in “not-the-new-one-anyway” Wink | ;-) Wink | ;-) Wink | ;-)
 
Nish

 

Author of the romantic comedy

Summer Love and Some more Cricket [New Win]

Review by Shog9
Click here for review[NW]

GeneralRe: old unmanaged world?? HahahamemberChristian Graus8-Oct-02 15:40 
I think the issue is that 'unmanaged' has a negative connotation - Microsoft will pull people into the .NET world more by marketing than by actual need.

 
Christian
 
Hey, at least Logo had, at it's inception, a mechanical turtle. VB has always lacked even that... - Shog9 04-09-2002
 
During last 10 years, with invention of VB and similar programming environments, every ill-educated moron became able to develop software. - Alex E. - 12-Sept-2002

GeneralRe: old unmanaged world?? HahahamemberMiguel Lopes10-Sep-02 7:39 
Tottaly agree!
In two years, guys like Nish wont even use pointers any more, "that belongs to the old world, power to script code! You want a Word-like processor? Just let me get my MS-INCREDIABLYSLOW-XXXML-ZCOM++++ script!".
 
Managed code sucks! If you cant clean up your garbage, ...well...live in the dirt!
GeneralI still prefer C - style castsmemberNemanja Trifunovic24-Aug-02 7:44 
Great article, Nish. However, in practice I use only dynamic_cast, which is really a form of RTTI and for all other casting, I just use good old C-style casts. To be honest, I don't buy this argument about C++ casts being safer, and it surely saves me a lot of typing. Poke tongue | ;-P
 
However, I agree that casting is often a sign of bad design. Smile | :)
 
Beer | [beer]
GeneralRe: I still prefer C - style castseditorNishant S24-Aug-02 17:19 
Hi Nemanja,
 
I made my move to C++ casts because the warnings were annoying me and I had no idea of how to disable them Blush | :O
 
But then I started having problems because I didn't know which cast to use and when to use them. As you said, in some cases C-style casts are easy on the typing fingers.
 
Then there is another issue for C# coders because C# casts resemble C-style casts.
 
Anyhow I like the look of the C++ casts, they make the code better looking and self explanatory Smile | :)
 
Thanks,
Nish
 

Author of the romantic comedy

Summer Love and Some more Cricket [New Win]

Review by Shog9
Click here for review[NW]

GeneralRe: I still prefer C - style castssitebuilderMichael Dunn24-Aug-02 19:06 
Nishant S wrote:
they make the code better looking

Really? I think they're horrible-looking and create too much noise in the code. This is especially the case when you're using the straight APIs or ATL/WTL, since you have to reinterpret_cast back and forth to LPARAMs or DWORDs a lot.

Plus, it's bloody hard to type "reinterpret_cast" Wink | ;)
 
--Mike--
Just released - RightClick-Encrypt v1.4 - Adds fast & easy file encryption to Explorer
My really out-of-date homepage
Sonork-100.19012 Acid_Helm

GeneralRe: I still prefer C - style castsmemberSoliant30-Aug-02 11:26 
Nishant S wrote:
I like the look of the C++ casts, they make the code better looking and self explanatory
 
Agreed. Anything that can make your code self-documenting is a good thing. Thanks for taking a complex topic that is very useful to everyday programming.
 
Nish when are you going to become a MVP, I think somebody of a higher power should nominate you.
 

Late.
 




Soliant | email
 
"The whole of science is nothing more than a refinement of everyday thinking." -Albert E.

GeneralRe: I still prefer C - style castsmemberChristian Graus27-Aug-02 1:55 
It's probably worth noting that C style casts are deprecated, although Stroustup is saying he'd like to reverse that in the name of C/C++ compatibility.
 
The C++ casts are ugly by design, to remind you that what you are doing is ugly.

 
Christian
 
We're just observing the seasonal migration from VB to VC. Most of these birds will be killed by predators or will die of hunger. Only the best will survive - Tomasz Sowinski 29-07-2002 ( on the number of newbie posters in the VC forum )
 
Cats, and most other animals apart from mad cows can write fully functional vb code. - Simon Walton - 6-Aug-2002

GeneralRe: I still prefer C - style castsmemberTim Smith8-Oct-02 15:29 
I'll take my ugly C/C++ casts any day over the alternative. I have seen far too many cases of programmers producing even more complex and crap code just trying to get around the lack of a good old ugly cast. Smile | :)
 
Not that you were saying casts should be removed.
 
Tim Smith
 
"Programmers are always surrounded by complexity; we can not avoid it... If our basic tool, the language in which we design and code our programs, is also complicated, the language itself becomes part of the problem rather that part of the solution."
Hoare - 1980 ACM Turing Award Lecture
GeneralRe: I still prefer C - style castsmemberChristian Graus8-Oct-02 15:38 
Tim Smith wrote:
Not that you were saying casts should be removed.
 
Not at all - I agree with you, the facility is there for a reason, being reminded not to overuse it is not the same as going out of your way to avoid having to use it.
 

 
Christian
 
Hey, at least Logo had, at it's inception, a mechanical turtle. VB has always lacked even that... - Shog9 04-09-2002
 
During last 10 years, with invention of VB and similar programming environments, every ill-educated moron became able to develop software. - Alex E. - 12-Sept-2002

GeneralRe: I still prefer C - style castsmemberAnna-Jayne Metcalfe18-Jul-03 0:56 
Christian Graus wrote:
The C++ casts are ugly by design, to remind you that what you are doing is ugly.
 
I couldn't have put it better myself! Wink | ;)
 
Anna Rose | [Rose]
 
Homepage | My life in tears
 
"Be yourself - not what others think you should be"
- Marcia Graesch
 
"Anna's just a sexy-looking lesbian tart"
- A friend, trying to wind me up. It didn't work.
 
Trouble with resource IDs? Try the Resource ID Organiser Visual C++ Add-In

GeneralRe: I still prefer C - style castsmemberTim Smith8-Oct-02 15:23 
static_cast is important since it helps protect you from some bugs. For example, when you have a class with multiple base classes, if you use a normal cast prior to the class being defined, you won't get an error. However, static_cast will generate an error.
 
class Example;
 
class Bob
{
    int i;
};
 
int SomeRoutine (Example *pe)
{
    Bob *pb = (Bob *) pe;    
}
 
class Tom
{
    int j;
};
 
class Example : public Tom, public Bob
{
};
 
Contrived example. However, if this bug ever bites you in the bug and you spend hours trying to figure out what is going on, it will make you a static_cast convert. Smile | :)
 
Tim Smith
 
"Programmers are always surrounded by complexity; we can not avoid it... If our basic tool, the language in which we design and code our programs, is also complicated, the language itself becomes part of the problem rather that part of the solution."
Hoare - 1980 ACM Turing Award Lecture
GeneralRe: I still prefer C - style castsmembersaierdia19-Nov-02 23:13 
but the code compiled ok even if that used static_cast .
i use vc6 .
GeneralRe: I still prefer C - style castsmemberbonamy20-Jan-03 2:41 
Sorry but if you use plymorphism then the dynamic_cast is much needed!
GeneralRe: I still prefer C - style castssussAnonymous20-Jan-03 4:55 

bonamy wrote:
Sorry but if you use plymorphism then the dynamic_cast is much needed!
 

Like I said: "However, in practice I use only dynamic_cast".
GeneralRe: I still prefer C - style castsmemberbonamy20-Jan-03 2:41 
Sorry but if you use polymorphism then the dynamic_cast is much needed!
Generaldynamic_cast by reference will throwsmemberPhilippe Mori24-Aug-02 7:42 
If dynamic_cast is done by reference, an standard C++ exception will be thrown. Here is an example:
 
dynamic_cast<ClassB &>(AnObject);

 
Philippe Mori
GeneralRe: dynamic_cast by reference will throwseditorNishant S24-Aug-02 17:19 
Hello Philippe
 
Thanks for all your very valuable and useful feedback Smile | :)
 
Nish
 

Author of the romantic comedy

Summer Love and Some more Cricket [New Win]

Review by Shog9
Click here for review[NW]

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130617.1 | Last Updated 24 Aug 2002
Article Copyright 2002 by Nish Sivakumar
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid