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.

trincot
  • 317,000
  • 35
  • 244
  • 286
Simplicity
  • 47,404
  • 98
  • 256
  • 385
  • @user588855 you need to know size of `c`'s memory size, or you are also interested in dynamic memory that Car's constructor can allocate? – UmmaGumma Jan 29 '11 at 09:13
  • [An `int` isn't necessarily four bytes](http://stackoverflow.com/questions/271076/what-is-the-difference-between-an-int-and-a-long-in-c/271132#271132). – GManNickG Jan 29 '11 at 09:36

4 Answers4

3

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

Asha
  • 11,002
  • 6
  • 44
  • 66
  • @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 '11 at 09: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 '11 at 09: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 '11 at 09: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 '11 at 09: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);
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
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.

David Titarenco
  • 32,662
  • 13
  • 66
  • 111
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);

Marlon
  • 19,924
  • 12
  • 70
  • 101