Struct Inheritance - Memory requirements

beakie (156)
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

1
2
3
4
5
6
7
8
9
10
11
12
13

struct parentstruct {
  char a;

  char getNum() { return a; };
};

parentstruct temp;

void main() {
  temp.getNum();
}




2) 1 byte? a

1
2
3
4
5
6
7
8
9
10
11
12
13

struct parentstruct {
  char a;

  virtual char getNum() { return a; };
};

parentstruct temp;

void main() {
  temp.getNum();
}




3) 2 bytes? a + b

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

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
helios (10126)
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.
BlackSheep (388)
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)
beakie (156)
Thanks. I appreciate your responses.
Topic archived. No new replies allowed.