Hi,
I have a
class A : public B {...member functions...... data members};
and am doing the following
A *p=new A();
void *p=static_cast< void *>(p);
factory_instanc e->process(p);
Here p is passed to a function, which accepts void ptr. That function
need to cast it back
A *pp=static_cast <A *>(p);
The function is in the factory which accepts void *p only, the specific
implementations need to cast the pointer back to the expected class
and use it.
Question:Though both works fine, yet I want to know what is more
appropriate in this situation static_cast OR reinterpert_cas t
The books suggests
static_cast= "For "well-behaved" and "reasonably
well-behaved" casts,including things you might now do without a cast
reinterpret_cas t=To cast to a completely different meaning. The key
is that you'll need to cast back to the original type to use it
safely.
But I am not able to interpret the sentences in this context :-) 24 4767
Rahul wrote:
>
and am doing the following
A *p=new A();
void *p=static_cast< void *>(p);
factory_instanc e->process(p);
Here p is passed to a function, which accepts void ptr. That function
need to cast it back
A *pp=static_cast <A *>(p);
Don't cast to void* before calling process(), it's not needed and the
less casts you have the better - just pass the A* as is like this:
A* pa = new A();
factory_instanc e->process(pa);
Casting back to A* inside process() should be fine.
It'd obviously be better if process() took an A* (or some Base-of-A*)
in the first place.
Rahul wrote:
Hi,
I have a
class A : public B {...member functions...... data members};
and am doing the following
A *p=new A();
void *p=static_cast< void *>(p);
factory_instanc e->process(p);
Here p is passed to a function, which accepts void ptr.
No need for a static_cast. You can convert a pointer to an object into a
pointer to void implicitly.
That function
need to cast it back
A *pp=static_cast <A *>(p);
The function is in the factory which accepts void *p only, the specific
implementations need to cast the pointer back to the expected class
and use it.
Question:Though both works fine, yet I want to know what is more
appropriate in this situation static_cast OR reinterpert_cas t
static_cast. Generally, one could say that you should choose static_cast
over reinterpret_cas t if it does the job.
The books suggests
static_cast= "For "well-behaved" and "reasonably
well-behaved" casts,including things you might now do without a cast
reinterpret_cas t=To cast to a completely different meaning. The key
is that you'll need to cast back to the original type to use it
safely.
But I am not able to interpret the sentences in this context :-)
You could translate it to "reinterpret_ca st is more evil than
static_cast" ;-)
Hi,
static_cast is meant to be used for cases which the compiler would
automatically be able to convert, such as char to int and in your case
A* to void*. reinterpret_cas t is used, as the book mentions, for
low-level hacks, especially when you know what you are doing, eg:
struct S
{
int a, b;
};
int main()
{
S s;
s.a = 10;
s.b = 20;
int* p = reinterpret_cas t<int*>(&s);
cout << "a=" << *p << endl;
++p;
cout << "b=" << *p << endl;
}
Typically reinterpret_cas t should work where a static_cast works.
"Ideally" in C++ we should avoid using void* as much because we loose
type safety. Also in your case you do seem to be having a class
hierarchy (A,B), so using virtual functions with base ptrs would be
cleaner (if virtual fn overhead is not an issue).
Thanks and regards
Sonison James
Rahul wrote:
Hi,
I have a
class A : public B {...member functions...... data members};
and am doing the following
A *p=new A();
void *p=static_cast< void *>(p);
factory_instanc e->process(p);
Here p is passed to a function, which accepts void ptr. That function
need to cast it back
A *pp=static_cast <A *>(p);
The function is in the factory which accepts void *p only, the specific
implementations need to cast the pointer back to the expected class
and use it.
Question:Though both works fine, yet I want to know what is more
appropriate in this situation static_cast OR reinterpert_cas t
The books suggests
static_cast= "For "well-behaved" and "reasonably
well-behaved" casts,including things you might now do without a cast
reinterpret_cas t=To cast to a completely different meaning. The key
is that you'll need to cast back to the original type to use it
safely.
But I am not able to interpret the sentences in this context :-)
Rahul wrote:
The books suggests
static_cast= "For "well-behaved" and "reasonably
well-behaved" casts,including things you might now do without a cast
reinterpret_cas t=To cast to a completely different meaning. The key
is that you'll need to cast back to the original type to use it
safely.
If your books say that, burn them. That's not the definition of
static cast.
There are two meanings for static cast:
1. Forcing conversions that could happen anyway:
static_cast<int >(5.5)
2. With the exception of const conversions, reversing defined conversions:
class B { };
class D : public B { };
B* b = new D; // defined conversion D* ->B*
D* d = static_cast<B*> (b);
It is still incumbent on the application to determine the
validity of the second time type of cast. In this case
making sure that b contains an value that really is
convertable to D*.
I have a simple rule-of-thumb:
If you can use static_cast, then use static_cast.
If you can't use static_cast, then use reinterpret_cas t.
--
Frederick Gotham
Frederick Gotham wrote:
I have a simple rule-of-thumb:
If you can use static_cast, then use static_cast.
If you can't use static_cast, then use reinterpret_cas t.
I have a simple preceding rule:
If you can do it without a cast, do not use any cast.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Victor Bazarov posted:
Frederick Gotham wrote:
>I have a simple rule-of-thumb:
If you can use static_cast, then use static_cast.
If you can't use static_cast, then use reinterpret_cas t.
I have a simple preceding rule:
If you can do it without a cast, do not use any cast.
Naturally ; )
I tend to use the old-style casts now and again too, e.g.:
enum { len = 64U };
int array[len];
for(size_t i = len - 1; (size_t)-1 != i; --i)
Or if I need a reinterpret_cas t and a const_cast at the same time:
char const *pc = 0;
int *pi = (int*)pc;
/* A very contrived example, I realise! */
The major drawback of the new-style casts is that they take up far too much
horizontal screen space.
--
Frederick Gotham
Frederick Gotham <fg*******@SPAM .comwrote:
The major drawback of the new-style casts is that they take up far too much
horizontal screen space.
Yes, which should serve as a visual reminder that a design that relies
heavily on casts is perhaps not ideal.
--
like a rainbow in the dark.
dio posted:
Frederick Gotham <fg*******@SPAM .comwrote:
>The major drawback of the new-style casts is that they take up far too much horizontal screen space.
Yes, which should serve as a visual reminder that a design that relies
heavily on casts is perhaps not ideal.
I'm out of nappies now though, and I can judge sensibly as to when I should
use what kind of cast. Would you prefer:
int *p = reinterpret_cas t<int*>(
const_cast<char *>(pcc)
);
or:
int *p = (char*)pcc;
And,
size_t i = static_cast<siz e_t>(-1);
or:
size_t i = (size_t)-1;
(Second example is intended to supress a compiler warning)
--
Frederick Gotham This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Gary Labowitz |
last post by:
Am I doing this correctly? It is a sample program for my class.
#include <iostream>
using namespace std;
int main( )
{
int x=3, y=4;
|
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?
|
by: news.ir.com.au |
last post by:
Hi,
In the following code I get the compiler error:
error C2243: 'static_cast' : conversion from 'class B *' to 'class A *'
exists, but is inaccessible
I understand why I get this error and can usually get around the situation
by inserting a "using A::..." statement inside class B, however, due to this
being a static cast, what is the syntax?
|
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()) {
|
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
| |
by: Amit |
last post by:
Greetings.
I am having some problem while using a cast operation(static_cast and/or
dynamic_cast) between base and derived objects when passing to functions.
what I have is something like this..
template <class T>
class Node{
protected:
T e;
Node* left;
|
by: PengYu.UT |
last post by:
I see some code use static_cast<some_pointer_type>(0) instead of NULL
to describe null pointer. I'm wondering what is the pros and cons of
each way. Is there any reason why we should one verses the other.
|
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
|
by: Rahul |
last post by:
Hi,
Everywhere I read that static_cast<only work fine for the conversion
which are implicitly allowed by the compiler
hence the following does not work
int *i;
double *d;
d = i; // Compilation error ,
OK
i= static_cast<int *>(d); // Compilation error. OK
|
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 usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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...
|
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();...
|
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...
|
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |