[comp.lang.c++] Q: Object pointer arithmetic?

lpw@jvc.UUCP (Lance Welsh) (09/27/89)

How does pointer arithmetic work when:
  - the type of the pointer is of a base class type, and
  - the object pointed to is derived from that type, and
  - the size of the derived type changed by introducing new member variables?

For Instance,
#include <stdio.h>
class B { public: int b; B() { b=1; } };
class D : public B { public: int d; D() { d=2; } };
const int ARRAY_SIZE=10;
main ()
{ D d[ARRAY_SIZE];
  for (B* p=d; p<&d[ARRAY_SIZE]; p++)  // will p increment by 4 or 8?
    printf ("p=%x b=%d (size=%d)\n", p, p->b, sizeof(*p));
  }

Is this the same question as how does sizeof work in similar circumstances?

If it is said that it is OK for sizeof to compute its value with compile-time
type information, ignoring what it may point at during run-time, OK.
But that does not seem to work so well with pointer arithmetic.

Just curious - apologies if it has been covered before.

-Lance P. Welsh  uunet!jvc!lpw  JVC Laboratory of America  (408) 988-4675

ark@alice.UUCP (Andrew Koenig) (09/28/89)

In article <543@jvc.UUCP>, lpw@jvc.UUCP (Lance Welsh) writes:

> How does pointer arithmetic work when:
>   - the type of the pointer is of a base class type, and
>   - the object pointed to is derived from that type, and
>   - the size of the derived type changed by introducing new member variables?

You can only do arithmetic on a pointer if you know the actual
type of the object to which it points and that object is an
element of an array.
-- 
				--Andrew Koenig
				  ark@europa.att.com