Pointer Size

There is some subtle point I didn't understand.

1
2
3
Pet *p;

p = new Dog;


Known that Dog is derived from pet...

But p is a pointer that point to a pet variable...the size of pet < dog so how can it have enough space for additional component from Dog ?

I'm in need for a reply,thanks in advance.
A pointer is generally the same size as an int (often 4 bytes). Always. A pointer is just a number. One number. That's all. Just one number.

In your code, somewhere else in memory is an object of type Dog. Could be huge. A million bytes. That Dog object is in memory. It has a memory address. That memory address is one number. Every object in memory, no matter how big or small it is, has a memory address that is just one number.

The pointer contains that memory address. That's all. Just one number.
Last edited on
char *p and int *n are pointers too,and they're number,but since the computer know that char is for type char is can jump 8 bits when we do arithmetic,since 8 bits = 1 byte.

pet *p has the bytes needed for pet,but since pet < dog so p = new dog can perform arithmetic on pointer ?
pet *p has the bytes needed for pet,but since pet < dog so p = new dog can perform arithmetic on pointer ?

Sure, but dereferencing the resulting pointer is only allowed when it points to a valid pet instance in an array of pets. Since an array can only have objects of one type (i.e. a pet array cannot contain any dog objects), there's no problem.
Topic archived. No new replies allowed.