### Struct Inheritance - Memory requirements

How many bytes of memory will each of these examples require once getNum() has finished executing?

Assuming a char is 1 byte and a pointer is 4?

1) 1 byte? a

 ``12345678910111213`` `````` struct parentstruct { char a; char getNum() { return a; }; }; parentstruct temp; void main() { temp.getNum(); } ``````

2) 1 byte? a

 ``12345678910111213`` `````` struct parentstruct { char a; virtual char getNum() { return a; }; }; parentstruct temp; void main() { temp.getNum(); } ``````

3) 2 bytes? a + b

 ``12345678910111213141516171819`` `````` struct parentstruct { char a; virtual char getNum() { return a; }; }; struct childstruct_one : public parentstruct { char b; char getNum() { return a + b; }; }; childstruct_one temp; void main() { temp.getNum(); } ``````

4) 6 bytes? a + b + pointer

 ``1234567891011121314151617181920`` `````` struct parentstruct { char a; virtual char getNum() { return a; }; }; struct childstruct_one : public parentstruct { char b; char getNum() { return a + b; }; }; parentstruct * temp; void main() { temp = new childstruct_one; temp.getNum(); } ``````

Is this right, please?
Last edited on
1. Probably.
2. No. The virtual table takes up space. Exactly how much will depend on the implementation.
3. No. See #2.
4. Doubly no. There's an inherent space overhead when using dynamic allocation, the exact value of which again depends on the implementation. Also see #2.

Although I know what you meant, I'd just like to point out that asking about space requirements for things that are not dynamically allocated is somewhat pointless.
Note that per instance of a derived class you don't have a full virtual table, just a pointer to the table. (Or multiple pointers in the case of multiple inheritance)
Thanks. I appreciate your responses.
Topic archived. No new replies allowed.