c++ - dereferencing typecasted void *object pointers -


with regards piece of code:

#include <iostream>  class cclass1 { public:     void print() {         std::cout << "this should print first" << std::endl;     } };  class cclass2 { public:     void print() {         std::cout << "this should print second" << std::endl;     } }; 

so asked interesting question having "free pointer" (so speak) can point multiple instances of different objects without having create new type of object. person had idea pointer can of type void * , since void, can made point instance of object , access object's public properties.

the following solution submitted:

int main() {     void *pclass(null);     ((cclass1 *)(pclass))->print();     ((cclass2 *)(pclass))->print();     std::cin.ignore();     return 0; } 

my question why above work, doesn't:

int main() {     (cclass1 *fg)->print();     (cclass2 *fg)->print();     std::cin.ignore();     return 0; } 

your first example exhibits undefined behavior, calling non-static member function via pointer doesn't point valid object. appears work accident, because function in question happens not use this in way.

your second example is, quite simply, syntactically incorrect. i'm not sure trying there; code makes no sense.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -