C ++ Class Object creation process (space allocation, assignment and initialization, object initialization sequence, virtual function table pointer)

Source: Internet
Author: User


When you first see this question, you may have some questions: Is there anything to say about creating C ++ class objects? Isn't it just calling Constructors? In fact, the situation is not as simple as imagined. A large number of details are hidden or ignored, and these details are the key to solving some other problems, therefore, it is necessary for us to go deep into this "mysterious" area and explore little-known secrets.

Allocate space (Allocation)
The first step to create a C ++ class object is to allocate memory space for it.For global objects, static objects, and objects allocated to the stack area, the memory allocation is completed at the compilation stage. For Objects allocated to the stack area, they are dynamically allocated during running. The memory space allocation process involves two key issues: the size of the space to be allocated, that is, the size of class objects.This problem is not a problem for the compiler, because the size of the Class Object is determined by it. It is the most clear about how much memory to allocate.

Whether there is enough memory space for allocation. For different situations, we need to analyze specific problems: Global Objects and static objects. The compiler will divide them into independent segments (Global segments) and allocate enough space for them. This generally does not involve insufficient memory space. Objects allocated in the stack area. The size of the stack area is determined by the compiler settings. Regardless of the specific settings, it always has a specific value, so the stack space is limited, objects allocated in the stack area that exceed the size of the space will cause stack area overflow, because the stack area allocation is completed in the compilation phase, therefore, an exception in the compilation phase will be thrown when the stack area overflows. Objects allocated in the heap area. The heap memory space is allocated at run time. Because the heap space is also limited, attempts to allocate a large number of objects simultaneously in the stack area will cause the allocation to fail, normally, a running exception is thrown or a meaningless value (usually 0) is returned ).

This stage is the most mysterious and easily overlooked stage in the process of object creation. If you want to know the specific tasks completed at this stage,The key is to distinguish two confusing concepts:Initialization)And assignment ). Initialization is performed with the birth of an object before the value assignment. The value assignment gives an object a new value after it is generated. Here I come up with a good example:When a baby is born in a hospital, the hospital will give it a mark to prevent confusion with other babies. This mark is usually the number of the bed where the baby mother is located, the process in which a hospital identifies a baby can be considered initialization. Of course, when a baby's parents get a name for them, the process of naming can be considered as a value assignment.After initialization and assignment, other people can identify them by their names. After distinguishing these two concepts, we will go to the analysis of object initialization.Class object initialization is actually to initialize all data members in the class object.C ++ has provided us with the ability to initialize class objects. We can implement the initialization list of Constructor (memberinitialization

The initialization list is executed before the code in the constructor body;
The initialization list does execute the initialization process of the data member. This can be seen from the call of the constructor of the member object.

After the object is initialized, we can still assign values to it. Same as class object initialization,The assignment of class objects is actually to assign values to all data members in class objects..C ++ has also provided us with this capability, which can be achieved through the implementation body of the constructor (that is, the part of the constructor wrapped.This can also be done from the assignment operator of member objects in the assembly code above.
(Operator =) The call is confirmed.

With the last line of code executed by the constructor, it can be said that the process of creating class objects will be completed successfully.

From the above analysis, we can see that the constructor implements the initialization and assignment processes of objects:Object initialization is completed through the initialization list, while object assignment is through the constructor, or more accurately, it should be the implementation body of the constructor.

Virtual function table pointer (vtable pointer)
How can we ignore the virtual function table pointer? Without it, the C ++ world would be much more clean.What we are most concerned about isClasses with virtual functions, when are the virtual function table pointers assigned to their class objects?? We do not have any code or capabilities (except for brute force cracking ).When a class object is created, the virtual table pointer is assigned a value, which is secretly completed by the compiler. The specific time is after the virtual function is entered, before initializing and assigning values to data members of an object, the compiler secretly assigns values to the virtual table pointer.. We can clearly see that, at the very beginning of the constructor, before entering the constructor body, or even before entering the initialization list, the compiler inserts code and assigns a value to the virtual table pointer with the virtual table address of the class being constructed.

It is hard to imagine that the process of creating a simple class object contains so many secrets if you do not practice and analyze it yourself. Knowing these secrets opens the door to victory for us to solve other problems. I will try some of the following questions. I wonder if you will be able to feel enlightened after reading this article:
1.Why does C ++ need to provide an initialization list? In which cases must the initialization list be implemented? (Note: In some cases, values can only be initialized but cannot be assigned)
2.Can constructor be a virtual function? What are the results of calling a virtual function in the constructor? (Note: The virtual table pointer is initialized at the beginning of the constructor)
3.What is the difference between constructor and the value assignment operator =? (Tip: differentiate between initialization and assignment)

Object initialization sequence:

When there is no virtual base class: Perform the base class constructor according to the declared sequence during the inheritance, In order to initialize the inherited part; initialize the member object in the declared order of the member object in the class. This is because the member object must be initialized before the object is created. This part can be carried out in the constructor initialization list; execute the constructor of the subclass to initialize each part.

When there is a virtual base class: the first step should be to initialize all the sub-objects of the virtual base class from top to bottom according to the position they define in the class, then perform initialization according to the above steps.

# Include <iostream> using namespace STD; Class A {public: A (int I) {cout <I <"constructor of a" <Endl;} () {cout <"constructor of a" <Endl ;}~ A () {cout <"desconstructor of a" <Endl ;}}; Class B: Public A {public: // note that static member objects are special, static A A1; a A2; A A3; B (): A2 (A (2) will be initialized during compilation )) {cout <"constructor of B" <Endl ;}~ B () {cout <"desconstructor of B" <Endl ;}}; a B: A1 = A (1); int main () {B; return 0 ;}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.