Im having a little problem with classes.
In code:
class A
{
public:
int num;
sayNum() { cout<<num;}
};
class B : public A
{
public:
sayNum() { cout<<"my num is: "<<num;}
};
/*somewhere else...*/
A foo[10];
B something;
something.num=10;
foo[0]=something;
foo[0].sayNum();
/*...*/
When I call foo[0].sayNum(); it prints “10”, and I would like it to print “my num is: 10”. I can’t change the type of the array. Note that it is just an example code, if I paste mine here it would be hard to understand :D)
This line:
copies something into the array. Because the type of
something(i.e. class B) is not the same as the type offoo[0](i.e. class A), there is a conversion. In this case,somethingwill be sliced, and only the A part will survive.The net result is that
foo[0]still contains an object with typeclass A, and thus the “my num is” will never be output.Changing
sayNum()to be virtual, which is good advice to solve other problems your code will show, won’t help in this case.How to solve it, depends on what you want to achieve. Possible solutions are:
A* foo[10];Note: this means you’ll have to use ‘new’ and ‘delete’.std::vector<A*> foo;Additional benefit: a vector can grow and shrink on demand.std::vector<std::shared_ptr<A> > foo;Additional benefit: no worries aboutdeleteanymore.But without knowing what you want to achieve, it is impossible to suggest the correct approach.