473,320 Members | 1,872 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

beginner's question on static_cast and const_cast

when are the use of static_cast and const_cast essential ?
Stroustrup, in his book TC++PL(3rd edition) in page number 139
(in Section 6.5 Advice - [4]), has advised
"Avoid explicit type conversion(casts)"

Given this, why do we have static_cast and const_cast
provided by the language ?

Kindly explain

Thanks
V.Subramanian

Nov 14 '07 #1
4 2441
<su**************@yahoo.comwrote in message
news:11**********************@k35g2000prh.googlegr oups.com...
when are the use of static_cast and const_cast essential ?
Stroustrup, in his book TC++PL(3rd edition) in page number 139
(in Section 6.5 Advice - [4]), has advised
"Avoid explicit type conversion(casts)"

Given this, why do we have static_cast and const_cast
provided by the language ?
I use a library written by someone else (I don't have the code to it, just
an interface). Originally he did not write the function calls constant
correct, so would have things like:

void drawtext( char* Text, int x, int y );

Now, I'm using std::strings To use this function with my std::strings poses
a problem, as a string.c_str() returns a const char*, and you can not call a
function expecting a non constant pointer with a constant pointer. I
verified with the developer that the function did not change the string, and
so I could do this:

drawtext( const_cast<const char*>( MyString.c_str() ), x, y )

a bit ugly but it does the trick. It throws away the constantness. Usually
this would be used when interfacing with C functions or C++ functions that
are not constant correct. This would do the same thing the C style cast of:

drawtext( (const char*)MyString.c_str(), x, y )
would do. But one of the advantages of making so verbose is we want to get
rid of them. I talked to the developer and he went through and made the
functions constant correct which allowed me to use:

drawtext( MyString.c_str(), x, y )

There are reasons for static cast also, sometimes to just make the compiler
shut up about warnings without having to disable them, sometimes to cast
variables explicitly.

static_cast is not really as dangerous as reinterpret_cast though. Unless
you know what you are doing and think about all the consenquences
reinterpret_cast can get you in deep water. I find it useful, however, when
extracting binary data from some data.
Nov 14 '07 #2
su**************@yahoo.com, India wrote:
when are the use of static_cast and const_cast essential ?
Stroustrup, in his book TC++PL(3rd edition) in page number 139
(in Section 6.5 Advice - [4]), has advised
"Avoid explicit type conversion(casts)"
He is right. Avoid them if _possible_.
Given this, why do we have static_cast and const_cast
provided by the language ?
Sometimes casts are just _necessary_. When you have to use one, you have to
decide which casting mechanism is appropriate. Const_cast should only be used to
"cast away" constness. I have only ever seen const_casts in relation to
non-const correct APIs.

Static_cast is necessary when you want to down-cast a pointer of some base class
into a pointer of a derived class. Static_cast does not make any checks as
dynamic_cast does. Static_cast if often used when either run-time type
information are not available for the code or when you want to avoid the
overhead of a dynamic_cast.

As general rule of thumb one can say that the need for dynamic_casts means that
your design is broken. I only use dynamic_casts in conjunction with Microsoft's
MFC library (which suffers from numerous design flaws, but it was engineered
quite a long time ago). If you use templates excessively (especially the
Curiously Recurring Template pattern), you'll come to the point where you have
to use static_casts quite often.

Regards,
Stuart
Nov 14 '07 #3
Stuart Redmann wrote:
Static_cast is necessary when you want to down-cast a pointer of some
base class into a pointer of a derived class.
That's not the only use for static_cast. It can also be legitimately
used in things like: int i = static_cast<int>(aDouble);
Nov 14 '07 #4
Stuart Redmann wrote:
Static_cast is necessary when you want to down-cast a pointer of some
base class into a pointer of a derived class. Static_cast does not make
any checks as dynamic_cast does. Static_cast if often used when either
run-time type information are not available for the code or when you
want to avoid the overhead of a dynamic_cast.
Also for round-tripping to void*:

T* pT;
// ...
void* pVoid = pT;
// ...
pT = static_cast<T*>(pVoid);

Often used with APIs that require a C callback.
Nov 14 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: buds | last post by:
Hi all, Following is the assigment operator of a derived class Derived& Derived::operator=(const Derived& inDerived) { //to assign to the base class object the following statement ...
1
by: Dave Rahardja | last post by:
Is there a difference between a static_cast and an C-style type cast? In other words, is there a difference between... int a; unsigned b = static_cast<unsigned>(a); // static_cast unsigned c...
11
by: Scott Brady Drummonds | last post by:
Hi, everyone, I've checked a couple of on-line resources and am unable to determine how reinterpret_cast<> is different from static_cast<>. They both seem to perform a compile-time casting of...
26
by: Steven T. Hatton | last post by:
The code shown below is an example from the Coin3D documentation. I believe the use of the C-style cast is safe under the circumstances, but from what I've been exposed to (TC++PL(SE)), I would...
3
by: shrishjain | last post by:
Hi All, Do people frequently use static_cast, const_cast etc in industry?.. I only saw them in books, and never in real code.. Shrish
1
by: PengYu.UT | last post by:
Hi, An example usage of static_cast is at http://publib.boulder.ibm.com/infocenter/macxhelp/index.jsp?topic=/com.ibm.vacpp6m.doc/language/ref/clrc05keyword_static_cast.htm But I don't...
7
by: Peter | last post by:
I never used reinterpret_cast -- probably because I don't know what it means. Can somebody enlighten me? I looked into Stroustrup's "The annoted C++ reference manual" -- but this was no help....
1
by: =?utf-8?B?5Zyw55CD5Y+R5Yqo5py6?= | last post by:
In C++ we can not overload the explicit typecast operator like static_cast, dynamic_cast, const_cast and reinterpret_cast. The only we can do is the implicit typecast operator like operator...
5
by: jason.cipriani | last post by:
There have been some recent threads about casting pointers to and from void* that have me rethinking some of my usual practices. I have a couple of questions. 1. What is the purpose of C++'s...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.