c++ - cpp store the objects in an array of pointer -


i trying c++.

void showcontensofarray(void *data[]) {       //in function have display values of respective objects.        //  ideas how do it? } int main(){     phew(xxx,abcdefg); //object of class      b ball(90),ball2(88);  //object of class b      void *dataarray[2];     dataarray[0] = &ph1;     dataarray[1] = &ball;     showcontentsofarray(dataarray); //function } 

void showcontensofarray(void *data[], int len) {     int i;     for(i=0;i<len;i++){         ((base*)(data[i]))->print();     } } 

and every class should have implementation of method print() knows how print values.

you use inheritance.

edit:

@ricibob's answer correct, if need casting inside function, need this:

#include <iostream>  using namespace std;  class base{ public:     virtual void print()=0; }; class a: public base{ public:      void print(){         cout<<"object a"<<endl;     } };  class b: public base{ public:     void print(){         cout<<"object b"<<endl;     } };  void showcontensofarray(void* data[], int len) {     int i;     for(i=0;i<len;i++){         ((base*)(data[i]))->print();     } }  int main(){     a;     b b;     void* v[2];     v[0]= &a;     v[1] = &b;     showcontensofarray(v,2);     return 0; } 

you can't evade inheritance.


Comments

Popular posts from this blog

python - How to create a legend for 3D bar in matplotlib? -

java - Multi-Label Document Classification -

php - Dynamic url re-writing using htaccess -