Sorry for the complicated title. I have something like this:
class Base
{
public:
int SomeMember;
Base() : SomeMember(42) {}
virtual int Get() { return SomeMember; }
};
class ChildA : public Base
{
public:
virtual int Get() { return SomeMember*2; }
};
class ChildB : public Base
{
public:
virtual int Get() { return SomeMember/2; }
};
class ChildC : public Base
{
public:
virtual int Get() { return SomeMember+2; }
};
Base ar[] = { ChildA(), ChildB(), ChildC() };
for (int i=0; i<sizeof(ar)/sizeof(Base); i++)
{
Base* ptr = &ar[i];
printf("El %i: %i\n", i, ptr->Get());
}
Which outputs:
El 0: 42
El 1: 42
El 2: 42
Is this correct behavior (in VC++ 2005)? To be perfectly honest, I expected this code not to compile, but it did, however it does not give me the results I need. Is this at all possible?
Yes, this is correct behavior. The reason is
initializes array elements by copying objects of three different classes onto objects of
class Baseand that yields objects ofclass Baseand therefore you observe behavior ofclass Basefrom each element of the array.If you want to store objects of different classes you have to allocate them with
newand store pointers to them.