I'm new to c++, I used python so I have a lot of doubts. My current problem is that I would like to have a list with different variables (like double, string or char), and none of the container objects that I have seen allows to do that (i have check array, vector, deque).
I need that because I have created different classes but all have the same functions names, so i would like to do something like
list[8].function(int arg);
but every element of the list is going to be of a different type. Is there a way to do a list wiht different type elements in c++ ?
//include required crap here
class Base {
public:
virtualvoid do_something() = 0;
};
class Derv1 : public Base {
public:
virtualvoid do_something() {
std::cout<<"Derv1 do_something()\n";
}
};
class Derv2 : public Base {
public:
virtualvoid do_something() {
std::cout<<"Derv2 do_something()\n";
}
};
int main() {
std::vector<Base*> my_vec; //make a vector of base pointers
my_vec.push_back(new Derv1); //since we have a vector of base pointers, we can also store
//Derv1* and Derv2* in it
my_vec.push_back(new Derv2);
my_vec.push_back(new Derv2);
for(unsignedint i = 0; i < my_vec.size(); ++i) {
my_vec[i]->do_something(); //call the virtual function
}
//EDIT: Forgot to delete the pointers I new'd
for(unsignedint i = 0; i < my_vec.size(); ++i) {
delete my_vec[i];
}
return 0;
}