Halaman

Minggu, 25 November 2012

[c++]Void Ptr storing your pointer to classes

A quick note, if you do store your inherited class, and then store them to a void pointer. Later on you call a method which is "public" from the parent class, please remember to static cast your void ptr to the parent class because:

DerivedClass *dc = new DerivedClass();
void *ptr = dc;

..
..
some mumbo jumbo.. :)
..
..

void SomeFunction(void *ptr)
{
BaseClass *base = (BaseClass*)ptr;
//this will give you access violation which willl gives you a head scratcher.. i've been there.. :'(
}

to fix above situation, you should

BaseClass *dc = new DerivedClass();
void *ptr = dc

//.. now it is safe to use
//that SomeFunction

..why?? dunno.. but it worth as a note.. well at least for me that is.. hehe ;) Cheers!

Tidak ada komentar:

Posting Komentar