Reprinted from: http://c.biancheng.NET/cpp/biancheng/view/2995.html Click to open link
When an object is created, the compiler allocates memory space for each object, including member variables and member functions.
The intuitive understanding is that if you define 10 objects, you should allocate memory space for the variables and functions of these 10 objects, as shown in:
Although each object has a different member variable, the code for the member function is the same, and the memory model above saves 10 copies of the same code fragment, wasting a lot of space.
in fact, the compiler stores member variables and member functions separately: allocates memory for each object's member variables, but all objects share the same segment function code. as shown in the following:
Take a look at one of the following examples:
[CPP]View PlainCopy
- #include <iostream>
- Using namespace std;
- Class demo{
- Public
- int A;
- float B;
- void display ();
- };
- void Demo::d isplay () {
- cout<<"a=" <<a<<", b=" <<b<<endl;
- }
- int main () {
- Demo obj;
- OBJ.A = 1;
- OBJ.B = 2;
- Obj.display ();
- return 0;
- }
Obj is both an object and a local variable in the main function, and the type is Demo, which allocates memory on the stack, just like a normal variable defined by int, char, and so on.
Assuming that the starting address of obj is 0X1000, then its memory distribution is as follows:
Both A and B are of type int, occupy 4 bytes of memory, and are arranged sequentially in the order in which they are declared, so the Obj object occupies a total of 8 bytes of memory. The reader can use the sizeof(obj) Statement Pro-Test.
The size of an object is only affected by member variables, and is not related to member functions. The member function allocates memory in the code area , not in the stack area.
C + + Learning Note----memory model for 2.4 C + + objects