1

If I want to allocate memory dynamically to an int object, I can do this:

int *x = new int;

In this case, I know that the heap reseves 4-bytes of memory for an int object.

But, if I have a user-defined class (type) and wanted to allocate memory dynamically, as follows:

Car *c = new Car;

How can I know the required amount of memory to be reserved on the heap for a Car object?

Thanks.

2

4 Answers 4

3

That will be the sizeof(Car) bytes. Compiler will do this automatically, you need not do anything specific.

4
  • @Ashot Martirosyan: Still when you do new only sizeof(pointer) is allocated. So above statement is still correct. It will be minimum (as it might be padded) sizeof(Car) bytes. Having pointer to dynamic memory won't change anything.
    – Asha
    Jan 29, 2011 at 9:05
  • when you are doing new you are calling constructor of Car, which can allocate dynamic memory. If asker mean only memory of Class itself, than your answer is correct.
    – UmmaGumma
    Jan 29, 2011 at 9:08
  • @Ashot Martirosyan: As far as I see, that is the question. In my view OP is asking what happens when you do new Car; i.e. how does the compiler calculate how much memory to allocate.
    – Asha
    Jan 29, 2011 at 9:11
  • 3
    @Ashot new calls the constructor, and the constructor does initialization. Any allocation done in the constructor has nothing to do with the size of Car since the Car has already been allocated...
    – Marlon
    Jan 29, 2011 at 9:32
2

See this article for information about how the size of a class object is determined. It's available to you programatically using:

size_t car_size = sizeof(Car);
2

You're looking for sizeof(). Note that this value may be larger than expected for user-defined types due to memory padding and/or alignment.

2

You want to use the sizeof operator. The sizeof operator returns the size of your type in bytes, and is evaluated at compile time. This is particularly useful for malloc since malloc requires you to specify how many bytes you need to allocate. However, you are using C++ and new does this automatically for you.

The sizeof operator returns the type size_t which is found in cstddef or stddef.h

Example code:

size_t size_in_bytes = sizeof(Car);

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.