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);
}
Output
Why am i getting 01010
[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:
alternitively you want to have your main like this:
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].
Arrays are not polymorphic.
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.
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
Popular Topics
Advertisement