1

code:

#include<iostream.h>
class base
{
   public:
   int bval;
   base(){ bval=0;}
};

class deri:public base
{
   public:
   int dval;
   deri() { dval=1; }
};

void SomeFunc(base *arr,int size)
{
   for(int i=0; i<size; i++,arr++)
       cout<<arr->bval;
   cout<<endl;
}

int main()
{
   base BaseArr[5];
   SomeFunc(BaseArr,5);

   deri DeriArr[5];
   SomeFunc(DeriArr,5);

   return 0;
}

Output:

00000
01010

I am not able to understand why the second line of output is 01010. This program is just for learning purpose, implemented in Turbo C++.

Himanshu Aggarwal
  • 1,803
  • 2
  • 24
  • 36
  • `` is not a standard header. I don't think Turbo has the proper ``, but then again, Turbo should pretty much be avoided at all costs. – chris Aug 14 '13 at 09:53
  • @chris in our universities, they follow Turbo C only. that is the reason. – Himanshu Aggarwal Aug 14 '13 at 09:55
  • @HimanshuAggarwal But you can download far better compilers for free. Even Microsoft's free compiler is more standard than this. – Mr Lister Aug 14 '13 at 10:00

1 Answers1

4

SomeFunc is expecting an array of base. In your first call in main you are passing an array of base, but in the second call you are passing an array of deri. deri objects are larger than base objects, so after the first arr++ in SomeFunc your pointer arr will not point to a base object anymore.

Memory layout of base is: [int bval]
Memory layout of deri is: [base, int dval]

DeriArr is [deri 0, deri 1, deri 2, deri 3, deri 4], so
[base 0, int dval 0, base 1, int dval 1, base 2, int dval 2, base 3, int dval 3, base 4, int dval 4]
or broken down:
[int bval 0, int dval 0, int bval 1, int dval 1, int bval 2, int dval 2, int bval 3, int dval 3, int bval 4, int dval 4]

SomeFunc starts with arr pointing to the start of the array. This is fine, but ++arr will not advance the pointer for one dval object (one int bval and one int dval) but only for one base object (one int bval only). As you can see after ++arr arr will point to [int dval 0, ...].

Werner Henze
  • 16,404
  • 12
  • 44
  • 69
  • can you be more precise please. thank you! i haven't understood the line "deri objects are larger than base objects". moreover why is the 2nd output 01010? – Himanshu Aggarwal Aug 14 '13 at 09:59
  • @HimanshuAggarwal Werner still has it right. In what way do you have troubles with "deri objects are larger than base objects"? Each base object contains one int, each deri object contains two ints. Twice the memory. But a pointer to base doesn't know about deri objects. – Mr Lister Aug 14 '13 at 10:02
  • @Himanshu Aggarwal: I updated my answer. I hope that makes it more clear to you. – Werner Henze Aug 14 '13 at 11:04
  • @WernerHenze very well answered. i was unaware of this behavior, indeed. thank you! – Himanshu Aggarwal Aug 14 '13 at 12:49