I am currently taking a course in c++, coming from a java background.
We've now gotten to the point where we talk about inheritance. This week's class didn't really explain what was needed to do the weekly assignments, leaving me somewhat at loss trying to solve them.
While I will be getting around to asking my tutor himself, that'd mean waiting until next week, putting me behind.
Allow me to demonstrate what I want to do:
class base
{
int field1;
base(int _field):
field1(_field){}
};
class subclass : public base
{
int field2;
public:
subclass(int _field2):
base(_field1),field2(_field2){}
string to_string()
{
return "I am a subtype!!";
}
};
int main()
{
vector<base> x;
x.push_back(subclass(123,456));
cout<<x[0].to_string[]<<end; //error!!
}
To my surprise, this code won't work, it won't even compile. The container x will cast the objects within it to the basetype, this means I am forced to treat what was once subtypes, as basetypes, which means that the subtypes variables and functions are out of reach.
What I want to do, is to treat the objects within the container as subtypes, IE typetesting(in itself a non-trivial matter) them and then do different things depending on what type the objects are.
This was trivial in java. There I could simply fill, say, an array of type base with subtypes and then go about doing whatever I wanted with the objects within.
I am assuming what I did in java, is supposed to be possible in C++, being able to place subtypes into some sort of container and then treat them as subtypes ought to be possible. It is evident I have missunderstood something fundamental here, this problem was entirely unforeseen to me.
It is worth mentioning that I tried this with both vector, and simple arrays. Exact same pattern emerged, the type of the array dictates how I can access the objects, ie I can't call to_string().
So to summarize: I wish to know how I can contain subtypes in containers without having my container casting the objects inside to the container's type.