1

I understand that certain data type object have certain buffer size. E.g. a char is 1byte. So, when creating a self-defined class object,

  1. How much memory is allocated to the object a?
  2. Is the amount of memory allocated different if the object is created on stack, or heap?
  3. Is the amount of memory allocated fixed, or can be changed?

Creating a user-defined class instance:

Animal a; //stack memory
a.makeSound();

Animal *a = new Animal(); //heap memory
a->makeSound();
2
  • 1
    BTW, Nitpicking: C++ makes no promise that a char takes one byte. C++ only promises that sizeof(char)==1. Nowhere is it specified that sizeof() returns the number of octets or bytes required to store its argument. A conforming implementation could store chars in 4 octets. (It's been done. And it wasn't an alignment thing.) Oct 21, 2010 at 13:50
  • @Eric Towers thanks for the correction.
    – seveleven
    Oct 21, 2010 at 15:43

3 Answers 3

3

In both cases at least sizeof(Animal) bytes will be allocated.

In case of stack allocation some extra memory might be used for alignment. In case of heap memory some extra memory will likely be used for storing heap service data. You can influence the exact amount of memory by changing the class - for example for heap allocation you can define a custom operator new for that class and make it allocate whatever you want amount of memory.

0
  1. The amount of memory needed to represent Animal depends on Animal's data members.
  2. The heap allocations use more memory than stack allocations since heap cells store meta informaion related to the heap related to each cell.
  3. In a strick sense the object size is fixes. However Animal may contain and own references to other heap objects. These heap objects can be changed at runtime.
0

How much memory is allocated to the object a?

Depends on Animal class definition.

Is the amount of memory allocated different if the object is created on stack, or heap?

No.

Is the amount of memory allocated fixed, or can be changed?

Depending upon 32-bit or 64-bit system and compiler specific implementations like padding etc, amount of memory allocated may vary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.