Original: http://blog.sina.com.cn/s/blog_586b6c050100dhjg.html
In C + +, there are two ways of creating objects:
Method One:
ClassName object (param);
This declares a type of object object that is classname, and C + + allocates enough storage space for all the members of the object.
Note: To conserve storage space, C + + allocates only the space that is used to hold data members when the object is created, and the member functions defined in the class are assigned to a common area in the storage space, shared by all objects of that class.
For example, I have defined a class like this:
Class Rec
{
Public
Rec (int width,int height);
~rec ();
int Getarea ();
Private
int rwidth;
int rheight;
};
When you rec Myrec (5,5), this creates a Myrec object, and then print out sizeof (MYREC), and you get 8 of this result.
Because there are 2 data members of type int in Myrec, an int member is 4 bytes, so the Myrec object occupies 8 bytes.
This method creates an object that allocates memory allocations to the stack, is created and revoked by the C + + default, and automatically calls constructors and destructors
Note: When an object created by this method invokes a class method, you must use "." Instead of "." (). such as Myrec.getarea ();
=============================================================================================
Method Two:
ClassName *object=new ClassName (param);
Delete object;
This approach is a bit like Java, and the same thing is that they all allocate memory on the heap to create the object (unlike the above), but the difference is that C + + returns an object pointer when it creates an object with new, which points to a ClassName object, C + + The only space allocated to object is the value of the pointer. Also, an object created dynamically with new must use DELETE to revoke the object. Only the Delete object will call its destructor.
Note: The object created by new does not use "*" or "." To access the member functions of the object, but with the operator "-";
For example: Rec *rec=new rec (3,4);
Rec->getarea ();
Delete rec;
By the way:
in general, the compiler divides the memory into three parts: static storage area, stack, heap. The static storage area mainly holds the global variables and static variables, and the stack stores the variables, addresses, etc. related to the function, and the heap stores dynamically generated variables. in C refers to the storage space freed by the malloc,free operation, which in C + + refers to the storage area where the new and delete operators function.
Two ways to "reprint" C + + to create objects