Re: Can I check the type of a void pointer

From: Martijn Lievaart (m_at_remove.this.part.rtij.nl)
Date: 12/02/03


Date: Tue, 02 Dec 2003 16:12:26 +0100

On Tue, 02 Dec 2003 09:57:28 -0500, Ron Natalie wrote:

>
> "Damon" <so_excited@excite.com> wrote in message news:159c8bc6.0312020650.178ee39@posting.google.com...
> ]
>>
>> So question to all the experts, can I check the type of a void pointer
>> or use some guaranteed way to elicit an exception without going
>> segmentation fault? BTW, I'm using g++ v3.2.2. I know that if i try to
>> delete the instances of the template class that was cast wrongly, it
>> segfault but I can't trap it!
>>
> No, once you cast a pointer to void*, you're only options are:
> check it against the null pointer constant.
> cast it back to exactly what it was before.
>
> The only solution I can suggest is to make your template class inherit
> from a common (public) base class and use that rather than void*. If
> the base class is polymorphic (has a virutal function), then you can use
> dynamic_cast to validate it against any particular derived class.

Adding to that, if you /need/ a void pointer (say for some C-ish
callback), you can use this technique as well. Cast to the base class.
Cast to void. Pass pointer. Cast back to base class. Use polymorphism
(virtual functions) or dynamic_cast<> from there.

HTH,
M4



Relevant Pages

  • Re: Can I check the type of a void pointer
    ... > cast it back to exactly what it was before. ... > from a common base class and use that rather than void*. ... > the base class is polymorphic (has a virutal function), ... if you /need/ a void pointer (say for some C-ish ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Dynamic casting at runtime
    ... curious if you can dynamically cast an object. ... So I was hoping to have an instance of the base class, ... string methodName = 'myMethod'; ... string propertyName = 'myProperty'; ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: new and override
    ... I can just cast it to the base class and call the method. ... The real reason for the 'new' keyword is backwards compatibility. ... > public virtual void Print() ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: warning C4238 : cast reference in void*
    ... Conversion from a typed pointer to a void pointer is implicitly done by the ... so a cast isn't necessary. ... CString foo2(CString aString) ...
    (microsoft.public.vc.language)
  • Re: Dynamic type convertion..
    ... As you already have a base class (it have to inherit from MBR to be ... if you cast the classes to the base class. ... Will you post an example with simple base class and 2 derived classes. ... >> public interface IMyObj ...
    (microsoft.public.dotnet.framework.remoting)