How does new know how much memory to allocate??

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mysticwater
    New Member
    • Aug 2010
    • 14

    How does new know how much memory to allocate??

    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!
  • johny10151981
    Top Contributor
    • Jan 2010
    • 1059

    #2
    sizeof works all the time :)

    Code:
    #include <stdio.h>
    
    class destiny
    {
    private:
    	int i;
    public : 
    	void seti(int j)
    	{
    		i=j;
    	}
    	int seti()
    	{
    		return i;
    	}
    };
    int main()
    {
     printf("%d\n",sizeof(destiny));
     return 0;
    }
    I am not a C++ Developer but yet. it worked without any error

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      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.

      Comment

      Working...