Output

Started by
5 comments, last by Dave Hunt 17 years, 11 months ago
Why am i getting 01010

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()
{
deri DeriArr[5];
SomeFunc(DeriArr,5);
}
Advertisement
Because arrays are evil.
Link was exactly spot on. Got it. Thank You.
[EDIT: Damn you Sneftel and your quickly typed link!!!]

Because the pointer arithmetic you are using to iterate the list is broken. You have an array of deri, but you are incrementing a pointer to base. In memory deri takes up more space than base. So incrementing a base class pointer will only offset you in memory the footprint of base. As such you are accessing random memory inside your array.

I'd suggest using the STL:

std::vector<deri> Derived;void SomeFunc(std::vector<deri> &Derived){    std::vector<deri>::iterator ite = Derived.end();    for ( std::vector<deri>::iterator it = Derived.begin(); it != ite; ++it )    {	  cout << (*it)->bval;    }    cout<<endl;}


alternitively you want to have your main like this:

base *myArray[5];//allocate the memoryfor ( int i = 0; i < 5; ++i ){    myArray = new deri();}SomeFunc(DeriArr,5);//now clean the memory when you are donefor ( int i = 0; i < 5; ++i ){    delete myArray;}
Because your base objects are smaller than your derived objects, meaning that, in somefunc(), when you read arr[1], you're actually halfway through DeriArr[0].

              0   1   2   3   4            +---+---+---+---+---+- ...Derived[]   |b|d|b|d|b|d|b|d|b|d|  ...            +---+---+---+---+---+- ...             0 1 2 3 4 5 6 7 8            +-+-+-+-+-+-+-+-+-+- ... Base[]   : |b|b|b|b|b|b|b|b|b|  ...            +-+-+-+-+-+-+-+-+-+- ...---->              0   1   2   3   4            +---+---+---+---+---+Derived[5]  |0|1|0|1|0|1|0|1|0|1|            +---+---+---+---+---+             0 1 2 3 4 5 6 7 8            +-+-+-+-+-+-+-+-+-+- ...arr         |0|1|0|1|0|1|0|1|0|1 ...            +-+-+-+-+-+-+-+-+-+- ...



Arrays are not polymorphic.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Fruny.. is it appropriate to be making comments about other people's DeriArr in a family friendly forum?
Quote:Original post by Anonymous Poster
Fruny.. is it appropriate to be making comments about other people's DeriArr in a family friendly forum?


LOL!

This topic is closed to new replies.

Advertisement