Sign in to follow this  

Output

This topic is 4248 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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);
}

Share this post


Link to post
Share on other sites
[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 memory
for ( int i = 0; i < 5; ++i )
{
myArray[i] = new deri();
}

SomeFunc(DeriArr,5);

//now clean the memory when you are done
for ( int i = 0; i < 5; ++i )
{
delete myArray[i];
}

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Fruny.. is it appropriate to be making comments about other people's DeriArr in a family friendly forum?

Share this post


Link to post
Share on other sites

This topic is 4248 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this