menu

hjk41的日志

Avatar

More Effective C++ 3: Never treat arrays polymorphically

Polymorphism and pointer arithmetic simple don't mix.
consider the following code:

class Base{...};
class Derived:public Base{...};

void foo(const Base & array[], const int n){
    for(int j=0;j<n;j++)
        print(array[j]);
}

Derived array[10];
foo(array,10);    // error here


What's wrong with this code? The problem is pointer arithmetic. When doing

 print(array[j]);

pointer arithmetic is performed. It equals to print( * (array+j) ). However, array is of type Base[], so the address you are getting is actually array+j*(sizeof(Base)) while the right one must be array+j*(sizeof(Derived))
So, don't treat arrays polymorphically, or you are just asking for trouble.

评论已关闭