472,958 Members | 2,228 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

Conversion from void* to a point of a class

I want to know to the following in a safe manner (the following code
will be dangerous if p does not contain a pointer to MyClass). I would
like someone to show me a better way (either throw an exception or
return value which I can check if the cast is allowed or not.

void* p;
...
MyClass* pClass = (MyClass*)p;

Thank you very much for your help.

Charles Zhang
Dec 11 '07 #1
7 1282
Hi Charles,
>void* p;
...
MyClass* pClass = (MyClass*)p;
>Thank you very much for your help.

initialize p == NULL, and check whether
p has some valid address pointing at before
you do the casting. NEVER use uninitialized
variables like you wrote here! They will point
to somewhere but not to your allocated memory
for your Class in this example!

something like:

void *p == NULL;

.....
.....
.....

if(p != NULL){
MyClass* pClass = (MyClass*)p;
}else{
//some invalid pointer handling code here
//a messagebox or some console output or whatever
//you like to handle this situation
}
Regards

Kerem

--
-----------------------
Beste Grüsse / Best regards / Votre bien devoue
Kerem Gümrükcü
Microsoft Live Space: http://kerem-g.spaces.live.com/
Latest Open-Source Projects: http://entwicklung.junetz.de
-----------------------
"This reply is provided as is, without warranty express or implied."
Dec 11 '07 #2
(MyClass*) is a C-style cast - in C++, reinterpret_cast, static_cast and
dynamic_cast are preferred. If you are not sure whether p really points
to a MyClass object or rather to an object of a different class, use
dynamic_cast:
http://msdn2.microsoft.com/en-us/lib...cs(VS.80).aspx

--Johannes

Charles Zhang wrote:
I want to know to the following in a safe manner (the following code
will be dangerous if p does not contain a pointer to MyClass). I would
like someone to show me a better way (either throw an exception or
return value which I can check if the cast is allowed or not.

void* p;
...
MyClass* pClass = (MyClass*)p;

Thank you very much for your help.

Charles Zhang

--
Johannes Passing - http://int3.de/
Dec 11 '07 #3
Of course, I will make sure the void pointer is not NULL. However, a
non-null pointer is not necessary a valid pointer of MyClass. Your code
will cause a run time error which could crash the application.

Charles Zhang


Kerem Gümrükcü wrote:
Hi Charles,
>void* p;
...
MyClass* pClass = (MyClass*)p;
>Thank you very much for your help.


initialize p == NULL, and check whether
p has some valid address pointing at before
you do the casting. NEVER use uninitialized
variables like you wrote here! They will point
to somewhere but not to your allocated memory
for your Class in this example!

something like:

void *p == NULL;

....
....
....

if(p != NULL){
MyClass* pClass = (MyClass*)p;
}else{
//some invalid pointer handling code here
//a messagebox or some console output or whatever
//you like to handle this situation
}
Regards

Kerem
Dec 11 '07 #4
Thank you very much. But I actually tried to use dynamic_cast, but I got
an compiler error

void* p = NULL;
....
....
MyClass* pClass = dynamic_cast<MyClass*>(p);

The compiler error is: "invalid expression type for dynamic_cast."

Then I changed the line to:
MyClass* pClass = dynamic_cast<MyClass*>((MyClass*)p);

Now, it compiles. But when p is not an valid pointer to MyClass, now run
time exception was thrown. Which could cause the application to crash.

Charles Zhang

Johannes Passing wrote:
(MyClass*) is a C-style cast - in C++, reinterpret_cast, static_cast and
dynamic_cast are preferred. If you are not sure whether p really points
to a MyClass object or rather to an object of a different class, use
dynamic_cast:
http://msdn2.microsoft.com/en-us/lib...cs(VS.80).aspx

--Johannes

Charles Zhang wrote:
>I want to know to the following in a safe manner (the following code
will be dangerous if p does not contain a pointer to MyClass). I would
like someone to show me a better way (either throw an exception or
return value which I can check if the cast is allowed or not.

void* p;
...
MyClass* pClass = (MyClass*)p;

Thank you very much for your help.

Charles Zhang



Dec 11 '07 #5
dynamic_cast requires a polymorphic type: p must point to an object with at
least one virtual function. Usually this kind of mistake is caught at compile
time, but due to indirection (p) compiler is not be able to do that (and of
course, an invalid pointer is not a polymorphic type).

Regards
--
Cholo Lennon
Bs.As.
ARG
"Charles Zhang" <Ch**********@newsgroups.nospamwrote in message
news:#Z**************@TK2MSFTNGP04.phx.gbl...
Thank you very much. But I actually tried to use dynamic_cast, but I got
an compiler error

void* p = NULL;
...
...
MyClass* pClass = dynamic_cast<MyClass*>(p);

The compiler error is: "invalid expression type for dynamic_cast."

Then I changed the line to:
MyClass* pClass = dynamic_cast<MyClass*>((MyClass*)p);

Now, it compiles. But when p is not an valid pointer to MyClass, now run
time exception was thrown. Which could cause the application to crash.

Charles Zhang

Johannes Passing wrote:
(MyClass*) is a C-style cast - in C++, reinterpret_cast, static_cast and
dynamic_cast are preferred. If you are not sure whether p really points
to a MyClass object or rather to an object of a different class, use
dynamic_cast:
http://msdn2.microsoft.com/en-us/lib...cs(VS.80).aspx

--Johannes

Charles Zhang wrote:
I want to know to the following in a safe manner (the following code
will be dangerous if p does not contain a pointer to MyClass). I would
like someone to show me a better way (either throw an exception or
return value which I can check if the cast is allowed or not.

void* p;
...
MyClass* pClass = (MyClass*)p;

Thank you very much for your help.

Charles Zhang



Dec 11 '07 #6
Well, that is true, dynamic_cast does not work for void-pointers - once
you have converted your MyClass* pointer to a void* you have voluntarily
given up all type information and there is no safe way back.

To convert a void pointer back to MyClass*, you have to use
reinterpret_cast, which in this context is basically the same as the
C-style cast you used initially. There is, of course, no guarantee that
the object returned by reinterpret_cast is indeed a valid object of
MyClass or rather some other garbage.

If possible by any measure, avoid using void-pointers in C++ in the
first place - there is almost always a better way to do it. In C, where
no such thing like RTTI exists, there is one common idiom you could use
in C++ as well if you are urged to use void pointers: To provide at
least a certain degree of sanity checking before using a casted pointer,
include some signature/magic field in the struct/class and check that it
contains the expected value before using it:

void *p = ...
MyClass *my = reinterpret_cast<MyClass*>(p);
if ( my->Signature != MYCLASS_SIGNATURE )
{
// this pointer is invalid
}
else
{
// it is likely the the pointer is valid
}

If you can avoid using void-pointers, do that - it may save you a lot of
trouble.

--Johannes

Charles Zhang wrote:
Thank you very much. But I actually tried to use dynamic_cast, but I got
an compiler error

void* p = NULL;
...
...
MyClass* pClass = dynamic_cast<MyClass*>(p);

The compiler error is: "invalid expression type for dynamic_cast."

Then I changed the line to:
MyClass* pClass = dynamic_cast<MyClass*>((MyClass*)p);

Now, it compiles. But when p is not an valid pointer to MyClass, now run
time exception was thrown. Which could cause the application to crash.

Charles Zhang

Johannes Passing wrote:
>(MyClass*) is a C-style cast - in C++, reinterpret_cast, static_cast
and dynamic_cast are preferred. If you are not sure whether p really
points to a MyClass object or rather to an object of a different
class, use dynamic_cast:
http://msdn2.microsoft.com/en-us/lib...cs(VS.80).aspx

--Johannes

Charles Zhang wrote:
>>I want to know to the following in a safe manner (the following code
will be dangerous if p does not contain a pointer to MyClass). I
would like someone to show me a better way (either throw an exception
or return value which I can check if the cast is allowed or not.

void* p;
...
MyClass* pClass = (MyClass*)p;

Thank you very much for your help.

Charles Zhang




--
Johannes Passing - http://int3.de/
Dec 11 '07 #7
Johannes Passing wrote:
Well, that is true, dynamic_cast does not work for void-pointers - once
you have converted your MyClass* pointer to a void* you have voluntarily
given up all type information and there is no safe way back.

To convert a void pointer back to MyClass*, you have to use
reinterpret_cast, which in this context is basically the same as the
C-style cast you used initially.
Johannes:

You can (and should) use static_cast to convert void pointer. Using
reinterpret_cast is usually an indication that you are doing something
non-portable (which casting a void pointer usually is not).

--
David Wilkinson
Visual C++ MVP
Dec 12 '07 #8

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

Similar topics

2
by: Thomas Matthews | last post by:
Hi, I'm working with Borland C++ Builder 6.2. My project uses the std::string class. However, Borland in its infinite wisdom has its own string class, AnsiString. To make my life easier, I...
3
by: Siemel Naran | last post by:
Here is a question about implicit conversion from T (&) to ptrcarray<T>. I wrote a class template <class T> struct ptrcarray { T * array; size_t size;
31
by: Bjørn Augestad | last post by:
Below is a program which converts a double to an integer in two different ways, giving me two different values for the int. The basic expression is 1.0 / (1.0 * 365.0) which should be 365, but one...
2
by: Alex Sedow | last post by:
Why explicit conversion from SomeType* to IntPtr is not ambiguous (according to standart)? Example: // System.IntPtr class IntPtr { public static explicit System.IntPtr (int); public...
9
by: Girish | last post by:
Im trying to understand implicit type conversions from object -> string and vice versa. I have two classes, one Driver and one called StringWrapper. These are just test classes that try and...
1
by: tsar.omen | last post by:
Hello everyone, during my coding practice I have encounted the following problem: Vital code pieces: --- template <class T> class SmartPtr {
2
by: Harold Howe | last post by:
Howdy all, I am getting a compiler error regarding a consrained conversion. It complains that it can't make the type conversion, even though the generic type argument inherits from the target of...
6
by: Peter Lee | last post by:
what's the correct behaver about the following code ? ( C++ standard ) I got a very strange result.... class MyClass { public: MyClass(const char* p) { printf("ctor p=%s\n", p);
4
by: tom | last post by:
I have a code segment list below, for the function call "calc()" in the main function, a standard conversion from "double"->"int" is made while "double"->"LongDouble" is also viable, does anyone...
2
by: xtrigger303 | last post by:
Hi to all, I was reading Mr. Alexandrescu's mojo article and I've a hard time understanding the following. Let's suppose I have: //code struct A {}; struct B : A {};
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
2
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

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.