which style of cast is correct to cast a void* into a class?

Is there a better way to do this?
 
MyClass* MyObject = (MyClass*)MyOtherObject->GetVoidObject( );


I don't think dynamic_cast is possible...

 
MyClass* MyObject = dynamic_cast<MyClass*>( MyOtherObject->GetVoidObject( ) );


Here's some extra information for you
1
2
3
4
5
6
7
8
public:
void* MyOtherClass::GetVoidObject( )
{
     return m_Object;
}

private:
void* m_Object;


There's a lot more that goes into my actual problem so if I am leaving anything crucial out or you just need more info let me know.

edit: FYI part of the reason I don't want to use a C-Cast is because I'm thinking about switching over to virtual inheritance rather than plain old inheritance
Last edited on
@ceruleus

static_cast you dummy!!!!
Here, static_cast and reinterpret_cast are equivilent.

Personally I'd go with reinterpret_cast just to be "safe".

Also, beware. consider the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Parent
{
 // .. stuff ..
};

class Child : public Parent
{
  // ... stuff ...
};

int main()
{
  Child c;
  void* p = &c;  // OK

  // this compiles okay but....
  Parent* p2 = reinterpret_cast<Parent*>(p);  // IT IS A BAD CAST!!!
}


The above might work in implementations but it isn't guaranteed to. EDIT: and if you're talking virtual inhertiance, then it probably won't work. /EDIT

You need to cast back to the exact same type from which you originally cast. In the above we cast from a Child*, so only a cast back to a Child* would be safe. A cast to a Parent* is not safe.

Bottom line is.. void pointers and inheritance just don't play nice together. Really, void pointers should just be avoided where at all possible.
Last edited on
"Bottom line is.. void pointers and inheritance just don't play nice together. Really, void pointers should just be avoided where at all possible. "

Yes I totally agree, unfortunately I don't think I have an alternative. Thanks for the help!
Unless you are working with a C-based API that forces you to use void pointers, then you have alternatives ;P
closed account (1yR4jE8b)
I'm not 100% sure here, but I think a reinterpret_cast and a C-style cast would have the exact same behaviour in this case.
You are correct. reinterpret_cast, static_cast, and C style casts all have the same effect here.

I just prefer reinterpret_cast because it's the most verbose and gives the clearest indication of what you're doing.
Topic archived. No new replies allowed.