Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

Is an array of Derived a kind-of array of Base?

array base derived kind-of
0
Posted

Is an array of Derived a kind-of array of Base?

0

Nope. This is a corollary of the previous FAQ. Unfortunately this one can get you into a lot of hot water. Consider this: class Base { public: virtual void f(); // 1 }; class Derived : public Base { public: // … private: int i_; // 2 }; void userCode(Base* arrayOfBase) { arrayOfBase[1].f(); // 3 } main() { Derived arrayOfDerived[10]; // 4 userCode(arrayOfDerived); // 5 } The compiler thinks this is perfectly type-safe. Line 5 converts a Derived* to a Base*. But in reality it is horrendously evil: since Derived is larger than Base, the pointer arithmetic done on line 3 is incorrect: the compiler uses sizeof(Base) when computing the address for arrayOfBase[1], yet the array is an array of Derived, which means the address computed on line 3 (and the subsequent invocation of member function f()) isn’t even at the beginning of any object! It’s smack in the middle of a Derived object. Assuming your compiler uses the usual approach to virtual functions, this will reinterpret the int i_ of t

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123