By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,984 Members | 2,794 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,984 IT Pros & Developers. It's quick & easy.

How does new know how much memory to allocate??

P: 14
Hi,
I was just wondering how the new operator (in C++) knows how much memory to allocate when creating an object of a class such as shown below:

i.e

class Books
{
...
}

int main()
{
....
Books textbook = new Books();
....
}

I have a stronger C background and I know that in C we have to specify the memory size for malloc(), using sizeof()....
But C doesn't have objects so this is where the comparison ends...

Also, I don't think the constructor call can specify the amount of memory for the whole object, since it only initializes the class fields (and even that is not required..), thus even though we are creating a new object, it doesn't make sense to have ... new Books() from a memory allocation standpoint. Please explain this too..
Thanks for your help!
Dec 17 '10 #1

✓ answered by weaknessforcats

Yes, the C++ new operator uses malloc and sizeof just like C to allocte memory for an object. However, C stops there. C++ continues on and calls the constructors for all of the member variables and then calls the class constructor. So in C++ you start witn a fully initialized object whreas in C you need to do the initialization yourself.

Share this Question
Share on Google+
2 Replies


100+
P: 1,059
sizeof works all the time :)

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2.  
  3. class destiny
  4. {
  5. private:
  6.     int i;
  7. public : 
  8.     void seti(int j)
  9.     {
  10.         i=j;
  11.     }
  12.     int seti()
  13.     {
  14.         return i;
  15.     }
  16. };
  17. int main()
  18. {
  19.  printf("%d\n",sizeof(destiny));
  20.  return 0;
  21. }
  22.  
I am not a C++ Developer but yet. it worked without any error
Dec 17 '10 #2

weaknessforcats
Expert Mod 5K+
P: 9,197
Yes, the C++ new operator uses malloc and sizeof just like C to allocte memory for an object. However, C stops there. C++ continues on and calls the constructors for all of the member variables and then calls the class constructor. So in C++ you start witn a fully initialized object whreas in C you need to do the initialization yourself.
Dec 17 '10 #3

Post your reply

Sign in to post your reply or Sign up for a free account.