Code:
class B {
public:
B () : b(++bCounter) {}
int b;
static int bCounter;
};
int B::bCounter = 0;
class D : public B {
public:
D () : d(0) {}
int d;
};
const int N = 10;
B arrB[N];
D arrD[N];
int sum1 (B* arr) {
int s = 0;
for (int i=0; i<N; i++)
{
s+=arr[i].b;
}
return s;
}
int sum2 (D* arr) {
int s = 0;
for (int i=0; i<N; i++)
{
s+=arr[i].b+arr[i].d;
}
return s;
}
Question:
What do these return:
1) sum1(arrB)=?
2) sum1(arrD)=?
3) sum2(arrD)=?
When I compile & run these, I get 55, 65, and 155, and have no idea why. I gather that in arrB the variables are b=1,2,3,…,10, and in arrD b=11,12,…,20, so I would’ve answered sum1(arrB)=55 and sum1(arrD)=155 as in sum of 11+12+..+20, and sum2(arrD)=155, because everywhere d=0.
What am I doing wrong?
You are getting object slicing.
You are passing a
D*array into a function that takes aB*array.Dis initially bigger thanB.Each time you are doing
s+=arr[i].b;you are moving the pointer by the size of B, while you need to move it by the size of D, so after each iteration the pointer is not moving one item forward.What happens in your particular case is that after each odd iteration it points to somewhere in the middle of the object of
Dclass. This is only happening becauseDis exactly twice as big asB, otherwise the behavior would have been different.