1. How to create objects in C ++
In C ++, we can use the following two methods to create an object,
- Dog dog; // Dog indicates the class name.
- Dog * p = new Dog ();
Both methods can create objects in C ++, but the processing in memory is completely different.
For the first method, dog is stored in the stack, and the occupied size is the sum of memory occupied by the member variables in the Dog class. The member methods are not included here, because the Member method is stored in the public storage area so that all the objects of this class can be accessed.
Figure 1 method 1 memory allocation for C ++ object Creation
The second method is different. This method uses pointers to open up a 4-byte space in the stack when * p is defined. When new Dog () is defined, a space is opened in the heap, then assign the first address of the space to * p, so that you can use * p to find any member method of the object in the heap.
Figure 2 method 2 memory allocation for C ++ object Creation
2. Java object Creation Method
In C ++, we have two ways to create objects. in Java, We only provide the following methods,
- Dog dog = new Dog();
During memory management, the JVM first allocates a space to the dog in the stack. When new Dog (); then, the actual space of the object is opened in the heap, then point dog to the space in the heap, so that we can use the member variables of the method object.
Figure 3 memory allocation in Java object Creation Mode
3. Summary
Through figure 2 and Figure 3, we will find that the method for creating an object in Java is very similar to the second method for creating an object in C ++. Besides the number of p and dog that I intentionally wrote, others are the same. Yes, they are very similar, but they are not exactly the same. In C ++, p is a pointer. With pointers, we can access any address in the memory, the memory can be processed freely. However, in Java, dog is a reference and can be understood as an encapsulation of pointers in C ++, we cannot directly perform address ++ operations in Java using pointers in C ++ to ensure Memory Security, this is a big difference between C ++ and Java.
I am very weak in writing. If you have unclear or improper descriptions, I hope you can correct them and thank you for your time.