473,756 Members | 6,028 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(cast s)"

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 2472
<su************ **@yahoo.comwro te in message
news:11******** **************@ k35g2000prh.goo glegroups.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(cast s)"

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<cons t 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_cas t though. Unless
you know what you are doing and think about all the consenquences
reinterpret_cas t 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(cast s)"
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
7382
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 static_cast<Base&>(*this)=inDerived;//works fine
1
20740
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 = (unsigned)(a); // C-style cast
11
5151
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 one type to another. However, I'm certain that there is something else that is happening. Can someone explain the difference or recommend an online site that can explain it to me?
26
2551
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 favor using a static_cast. Is there any technical reason to favor the C-style over a static_cast? http://doc.coin3d.org/Coin/index.html void foo(SoNode * node) { if (node->getTypeId() == SoFile::getClassTypeId()) {
3
1930
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
1920
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 understand why it is necessary to use float d = static_cast<float>(j)/v; Isn't float d = float(j)/v;
7
10912
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. Can I assume that reinterpret_cast is not safe and should not be used? Does it always succeed even if the cast is garbage?
1
7137
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 MyClass::MyDistType(). I agree there are maybe no meaning to overload dynamic_cast/const_cast/ reinterpret_cast, except the static_cast. If we enable the overloading of static_cast, we could be able to force the user doing type casting explicitly.
5
3912
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 static_cast<>? In other words, is there any real difference between statements like (with non-pointer types): double a = 3.4; int b = (int)a; // <--- this
0
10014
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8688
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7226
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6514
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5119
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5289
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3780
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3326
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2647
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.