That's the expected behavior.
When you assign the subclass object to the dyna-array that's expected to hold base class object, the assignment operator is called which doesnot copy the subclass object bit by bit. Instead, the assignment operator you define for base class or the assignemnt operator composed by the compiler is execute. All boiled down, the vptr is pointed the bass class virtual table. So literally they are all base class objects.
Your design is essentially problematic. To make your dynamic array to be able to hold all base class, subcalss1 , subclass2 objects, the three type has to has the same size. Or any clss derived from base calss are not expected to add new member variables.
Anyway, let's say this is what you want, It's achievable by some sort of hack --- copy it bit by bit.
Code:
class Base{
public:
Base():data(0){}
Base& operator=(const Base& rhs){
memcpy(this, &rhs, sizeof(*this));
}
virtual void whoAmI(){ std::cout<<"I am a base object and my data is "<<data<<std::endl;
}
protected:
int data;
};
class Subclass1: public Base
{
public:
Subclass1(){ data=1; }
void whoAmI()const{ std::cout<<"I am a Subclass1 object, and my data is "<<data
<<std::endl; }
};
...
try with the above code, you may get the behaviour you expected. I did not test the code, so you may need some extra work to make it work. Note it's not the right way of programming c++, but I belive it serves to make you understand the underlying mechanism of multi-morphism more deeply.
Bookmarks
Algorithms and Data Structures
Java tutorials
Algorithms Forum