Identifying objects
Hi guys, a quick question.
If I have a Base class, and say two derived classes A, and B with some virtual functions, and set things up thus.
1 2 3 4
|
std::vector<Base> base;
base.push_back(A());
base.push_back(B());
|
Then, in order to loop through the vector structure we would run a for loop like this
1 2 3 4
|
for(int i=0;i<base.size();i++){
}
|
Now, my question is this, without using any special identifier such as a enum
is it possible int the C++ language to do this...
1 2 3 4 5 6 7
|
for(int i=0;i<base.size();i++){
if(base[i]==(Object A)
//do this
if(base[i]==(Object B)
//do that
}
|
So far I have been using enums, and it seems very clunky. Any help would be greatly appresicated.
It can be done if you have the "==" operator properly overloaded in both of the derived classes.
Thanks unsensible, I will have a look at that.
Mike
This creates a vector of Bases, no A or B can be put into it
This copies ("slices") the Base part of A into the first position of the vector.
To build a collection of polymorphic objects, you need something more like
std::vector<std::unique_ptr<Base>> bases;
Last edited on
Topic archived. No new replies allowed.