473,545 Members | 2,113 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Would a static_cast be better style here?

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::getClas sTypeId()) {
SoFile * filenode = (SoFile *)node; // safe downward cast, knows the
type
}
else if (node->getTypeId().is OfType(SoGroup: :getClassTypeId ())) {
SoGroup * group = (SoGroup *)node; // safe downward cast, knows the
type
}
}

--
STH
Hatton's Law: "There is only One inviolable Law"
KDevelop: http://www.kdevelop.org SuSE: http://www.suse.com
Mozilla: http://www.mozilla.org
Jul 22 '05 #1
26 2519
"Steven T. Hatton" <su******@setid ava.kushan.aa> wrote in message
news:Xe******** ************@sp eakeasy.net...
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?

No, if you need a cast, use only the new C++ ones (static_cast,
dynamic_cast, reinterprer_cas t). They are there for a reason, to help you
identify potential problems. For example if your code crashes, the first
thing you will do is check the reinterpret_cas ts at first.


Ioannis Vranos

Jul 22 '05 #2
On Fri, 16 Apr 2004 16:14:17 +0300, Ioannis Vranos wrote:
"Steven T. Hatton" <su******@setid ava.kushan.aa> wrote in message
news:Xe******** ************@sp eakeasy.net...

Is there any technical reason to favor the C-style over a static_cast?


No, if you need a cast, use only the new C++ ones (static_cast,
dynamic_cast, reinterprer_cas t).


One advantage beeing that you can much more easily search for
static_cast<som ething>(variabl e) than (something) variable.

--
NPV

"the large print giveth, and the small print taketh away"
Tom Waits - Step right up

Jul 22 '05 #3

"Steven T. Hatton" <su******@setid ava.kushan.aa> skrev i en meddelelse
news:Xe******** ************@sp eakeasy.net...
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?


None whatsoever. Actually, I would advice you never ever use the C-style
cast. The only purpose of it is to be compatible with C.

/Peter
Jul 22 '05 #4
"Steven T. Hatton" <su******@setid ava.kushan.aa> wrote in message news:<Xe******* *************@s peakeasy.net>.. .
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?


Given the situation, you _probably_ want to use a dynamic_cast instead
of either one. Generally this is a type of situation you want to
avoid though -- except in a few situations like re-creating an object
that's been persisted to a stream of some sort, downcasting tends to
indicate poor design.

Downcasting gives you direct access to the functionality of a derived
class. Generally speaking, the preferred method of doing this is to
wrap that functionality in a virtual functio in the base class so you
can use it without casting down to the derived type.

Contrary to statements elsethread, a C-style cast can do one thing
none of the new casts can. It has nothing to do with the question at
hand, so I won't go into it, but it does exist.
Later,
Jerry.

--
The universe is a figment of its own imagination.
Jul 22 '05 #5
"Jerry Coffin" <jc*****@taeus. com> wrote in message
news:b2******** *************** **@posting.goog le.com...
"Steven T. Hatton" <su******@setid ava.kushan.aa> wrote in message news:<Xe******* *************@s peakeasy.net>.. .
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?


Given the situation, you _probably_ want to use a dynamic_cast instead
of either one. Generally this is a type of situation you want to
avoid though -- except in a few situations like re-creating an object
that's been persisted to a stream of some sort, downcasting tends to
indicate poor design.

Downcasting gives you direct access to the functionality of a derived
class. Generally speaking, the preferred method of doing this is to
wrap that functionality in a virtual functio in the base class so you
can use it without casting down to the derived type.

For downcasts static_cast is better to be used. dynami_cast is for upcasting
and crosscasting.

Contrary to statements elsethread, a C-style cast can do one thing
none of the new casts can. It has nothing to do with the question at
hand, so I won't go into it, but it does exist.

Don't tease our curiosity. Tell it. :-)


Ioannis Vranos

Jul 22 '05 #6
Ioannis Vranos wrote:

For downcasts static_cast is better to be used. dynami_cast is for upcasting
and crosscasting.


"Upcasting" is never necessary, as far as I can tell. dynamic_cast is
used for checked downcasting (e.g., if I cast from Shape to Triangle,
ensures that the Shape really was a Triangle).

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
Jul 22 '05 #7
"Kevin Goodsell" <us************ *********@never box.com> wrote in message
news:01******** ***********@new sread1.news.pas .earthlink.net. ..

"Upcasting" is never necessary, as far as I can tell. dynamic_cast is
used for checked downcasting (e.g., if I cast from Shape to Triangle,
ensures that the Shape really was a Triangle).

Yes my silly mistake. Downcasting and crosscasting is dynamic_cast about.
Upcasting needs no casting.



Ioannis Vranos

Jul 22 '05 #8
Ioannis Vranos wrote:
"Kevin Goodsell" <us************ *********@never box.com> wrote in message
news:01******** ***********@new sread1.news.pas .earthlink.net. ..

"Upcasting" is never necessary, as far as I can tell. dynamic_cast is
used for checked downcasting (e.g., if I cast from Shape to Triangle,
ensures that the Shape really was a Triangle).

Yes my silly mistake. Downcasting and crosscasting is dynamic_cast about.
Upcasting needs no casting.


OK, which way is up? Actually, I didn't even think about that issue. But now
that I think about it. A dynamic_cast would be the thing to use. Upcasting
actually means to cast from a derived to a base class, and _does_, I'm
pretty sure, require a static_cast.

This is a little exercise I made up to try to get a handle on all this.
It's a very tricky topic.
/* Hava Fun */
#include <iostream>
#include <string>
using std::ostream;
using std::string;
using std::cout;

class A{
public:
A(const string& name = "A"):m_name(nam e)
{}
virtual ostream& toString (ostream& out) const;
friend ostream& operator<<(ostr eam& out, const A& a);
protected:
string m_name;
};

ostream& A::toString (ostream& out) const{
return out << this->m_name;
}

ostream& operator<<(ostr eam& out, const A& a)
{
return a.toString(out) ;
}
class B:public A
{
public:
B(const string& name = "B"):A(name )
{}
ostream& toString (ostream& out) const;

};

ostream& B::toString (ostream& out) const{
A::toString(out );
return out << this->m_name;
}

ostream& operator<<(ostr eam& out, const B& b)
{
return b.toString(out) ;
}

int main()
{

A a;
B b;
A* aa_ptr = &a;
A* ab_ptr = &b;
B* bb_ptr = &b;
cout << "A* aa_ptr = &a: " << *aa_ptr << std::endl;
cout << "A* ab_ptr = &b: " << *ab_ptr << std::endl;
cout << "B* bb_ptr = &b: " << *bb_ptr << std::endl;

ab_ptr = static_cast<A*> (&b);
cout<<"ab_ptr = static_cast<A*> (&b): " << *ab_ptr << std::endl;

ab_ptr = dynamic_cast<A* >(&b);

cout << "ab_ptr = dynamic_cast<A* >(&b): " << *ab_ptr << std::endl;

cout << "cout <<(A)*ab_ptr << std::endl;: " <<(A)*ab_ptr << std::endl;

cout << "cout << static_cast<A>( *ab_ptr) << std::endl;: ";
cout <<static_cast<A >(*ab_ptr) << std::endl;

cout << "cout << *dynamic_cast<A *>(ab_ptr) << std::endl;: ";
cout << *dynamic_cast<A *>(ab_ptr) << std::endl;
}

--
STH
Hatton's Law: "There is only One inviolable Law"
KDevelop: http://www.kdevelop.org SuSE: http://www.suse.com
Mozilla: http://www.mozilla.org
Jul 22 '05 #9
Steven T. Hatton wrote:
class A{
public:
A(const string& name = "A"):m_name(nam e)
{}
virtual ostream& toString (ostream& out) const;
The next line is not necessary. It came from an earlier approach.
friend ostream& operator<<(ostr eam& out, const A& a);
protected:
string m_name;
};


--
STH
Hatton's Law: "There is only One inviolable Law"
KDevelop: http://www.kdevelop.org SuSE: http://www.suse.com
Mozilla: http://www.mozilla.org
Jul 22 '05 #10

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

Similar topics

7
7355
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
20705
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
5121
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...
3
1907
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
3
5984
by: Kobe | last post by:
Hi, if I need to convert a size_t to an int, in "older" C++ I'd write the following code (using C-like "casting"): <CODE> std::vector<...> v; int count = (int) v.size(); // v.size() returns size_t </CODE>
11
18155
by: esuvs81 | last post by:
Hi all. In short, is there any performance difference between: float f = 10.0f; int i = static_cast<int>(f); and float f = 10.0f; int i = int(f);
9
3158
by: Vincent RICHOMME | last post by:
Is there any reason to use static_cast instead of old C syntax ? Let's say I declare GLfloat test = static_cast<GLfloat>(x); or GLfloat test = (GLfloat) x;
5
3869
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; //...
0
7468
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7401
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7656
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. ...
1
7423
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
5972
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...
1
5329
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...
0
3450
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...
1
1884
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
0
704
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...

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.