I am trying to create a 2D dynamic array where each row would correspond to the list of different data type. For this purpose I am using a vector of pointers, where each pointer would point to a 1D array of a certain type. To create a generic array, I created a template class which I derived from an abstract class, so that I can use the abstract class pointers in my array(12009314). Following is the code where I am trying to do this but the problem is since I don't have the array pointer in the abstract class, I am not able to access the array elements:
class abs_attribute{
public:
virtual void insertAttribute(abs_attribute* a){}
virtual void print(){}
};
template <class T>
class attribute:public abs_attribute{
public:
T *data;
int size;
attribute(int s=3){
size=s;
data=new T[size];
}
void print(){
for(int i=0;i<size;i++)
cout<<data[i]<<" ";
cout<<"\n";
}
};
class Graph{
private:
vector<abs_attribute*>Attribute;
public:
Graph(){}
void insertAttribute(abs_attribute* a){
Attribute.push_back(a);
}
void printAttributes(){
for(int i=0;i<Attribute.size();i++){
for(int j=0;j<N;j++){
cout<<Attribute[i]->data[j]<<" ";//Not able to access data as it is not a member of abs_attribute
}
cout<<endl;
}
}
};
int main(){
abs_attribute* age=new attribute<int>(N);
age=new attribute<int>(N);
for(int i=0;i<N;i++)
static_cast<attribute<int>*>(age)->data[i]=rand()%50;
age->print();
Graph g;
g.insertAttribute(age);
g.printAttributes();
}
Is there any way to access data array inside the Graph class without knowing the template type of the derived class in advance? The main aim of this entire activity is to have an multiple arrays of different data types in my class. Since I cannot dynamically add data members to a class, I resorted to a vector where I'll keep pushing the array pointers, but this method became complicated due the requirement of the array elements being generic.