// B4.cpp - pass an array of objects or array of pointers to objects? // // Suppose you need access to a collection of derived objects inside some // function, and the class of the derived objects may be different in different // places in your program. Then, should you choose to use an array, it is // important that you use an array of pointers to the derived objects rather // than an array of the objects themselves. The reason for this is that // pointer arithmetic is not polymorphic. That is, when you increment a base // class pointer the location in memory pointed to moves by the size of a base // object, even if the pointer is attached to a derived object. #include using namespace std; class B { public: virtual void mf() { cout << "\n B::mf()"; } }; class D1 : public B { public: virtual void mf() { cout << "\n D1::mf()"; } private: float f; // here only to ensure that sizeof(D1) > sizeof(B) }; class D2 : public B { public: virtual void mf() { cout << "\n D2::mf()"; } private: double d; // here only to ensure that sizeof(D2) > sizeof(D1) }; void aFlawedFunction(B b[], int size) { for(int i=0; imf(); } //void noCompileFunction(B &b[], int size) { // for(int i=0; i