Advertisement

I have a pointer pointed to a class................

Started by July 01, 2000 10:51 AM
4 comments, last by FancyZero 24 years, 5 months ago
I have a void* pointer pointed to a class. How can I know, what the class is? the code: class a; class b; void* p p=&a How can I know,the pointer "p" is point to a class b or a class a??
I''m fairly sure you can''t.
A void pointer is a void pointer... the same way you can''t know what sort of struct a void pointer points to, you can''t know what sort of class either.
Advertisement
You use an abstract base class base, derive class a & b from it

Make a pure virtual function in the base class


    class base{public:virutal int ID() = 0;}class a : base{int ID(){return(1);}}class b : base{int ID(){return(2);}}//...winmain(){base* pbase;a classA;b classB;pbase = &classApbase->ID();  //returns 1pbase = &classBpbase->ID();  /returns 2//...}    


note that this is slow. very slow. If you need to speed it up, then you need to use dynamic_cast''ings
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
quote:
note that this is slow. very slow. If you need to speed it up, then you need to use dynamic_cast''ings


Umm... no.

A simple dereference for using a virtual function is not going to be any slower than a dynamic cast, which goes through the process of RTTI to get the type info, and returns a 0 if the cast is wrong.

The implementation of an ID() method is the fastest way, it is just a more high-maintenance method than allowing the language to do it for you.

I think it isn''t possible to getting out the class type on which the void pointer points.
But when you want to use functions from the class you have to use an cast-operator (I think they are called so):

b *temp = (b *) p;

I hope this could help you...
I know that MFC has support for such things, maybe you want to look at the MFC source take a look at some MFC documentation to see how they did it ?

I personally would prefer the metioned ID() method...

Tim

--------------------------
www.gamedev.net/hosted/glvelocity
glvelocity.gamedev.net
www.glvelocity.com
Tim--------------------------glvelocity.gamedev.netwww.gamedev.net/hosted/glvelocity

This topic is closed to new replies.

Advertisement