Need some help with class - type

Started by
2 comments, last by rip-off 13 years, 2 months ago
[color="#1C2837"][size=2]Hi all. I have a few classes and header files

//a.h
class a{

};

//b.h inherits from a
class b: public a{
private:
int var;
public:
b(int); //sets var as the int
int getVar(); //returns var
};

//c.h inherits from a
class c: public a{
private:
int var;
public
c(int); //sets var as the int
int getVar(); //returns var
};

//main.cpp
vector<a> aArray;
for(int i = 0 ; i &lt; 5 ; i++){
int randVal = rand()%2;
if(randVal==0){
b B(randVal);
aArray.push_back(B);
}
else{
c C(randVal);
aArray.push_back©;
}
}

for(int i = 0 ; i &lt; 5 ; i++){
a A = aArray;
//my problem, how would I know that a is actually b or c? Since b and c both are sub classes of c
}


basically after storing them in a vector, I want them to be able to be taken out in the same type as they were put in with.

Any ideas?&nbsp;</a><div><a>I want to take them out of the vector aArray as either an object of type b or type c then use getVar to retrieve the values</a></div><div><a>Thanks a lot.

</a>

</div>
Advertisement
For starters, you are "slicing" your data. A "vector< a >" can only store objects of type 'a'. Attempting to push_back() a 'b' results in "slicing" where only the relevant "a" portion of your "b" is stored. All the "b" data is lost. To get around this, you need to store pointers, like "boost::ptr_vector< a >". Then, when you push_back( new b ); your b is properly stored.

Next up, ask yourself "why you are doing this?". It is going to be slow, error-prone, and combersome to manage your data like this. It is better to store the objects in unique containers by type than to toss them all in an array and attempt to sort them out later.

As to the issue of retrieval? maybe boost::any is the solution you are looking for. If not, you can attempt to dynamic_cast<> your objects

b *myB = new b;
a *myB_as_A = myB;

if( dynamic_cast<b *>( myB_as_A ) != NULL )
{
b *someB = dynamic_cast< b * >( myB_as_A );
}
else if( dynamic_cast<c *>( myB_as_A ) != NULL )
{
c *someC = dynamic_cast< c * >( myB_as_A );
}
Thanks.

Now I have another problem. The polymorphism works fine now. However, if I declare a vector of type 'a' to store my objects of type 'b' and 'c', after I managed to put it in, when I take them out, data from them is lost. How should I go about preventing this?

Thanks a lot for your time.


If you have std::vector<a>, then it stores values of the type "a". It cannot store derived types. Attempting to do so causes object slicing, as Kulseran notes. If you want to store polymorphic objects, your collection needs to store pointers. Re-read Kulseran's post.

This topic is closed to new replies.

Advertisement