Usually we define a class, how much space it occupies it?
First we look at the following class
class A{
public:
void func1(void){
printf("11111heihei\n");
};
void func2(void){
printf("11111heihei\n");
};
public:
int number;
};
class B{
public:
void func1(void){
printf("heihei\n");
};
void func2(void){
printf("heihei\n");
};
public:
char number;
int number1;
};
We outputs of the two classes of length
1 #include <stdio.h>
2 class A{
3 public:
4 void func1(void){
5 printf("11111heihei\n");
6 };
7 void func2(void){
8 printf("11111heihei\n");
9 };
10 public:
11 int number;
12 };
13 class B{
14 public:
15 void func1(void){
16 printf("heihei\n");
17 };
18 void func2(void){
19 printf("heihei\n");
20 };
21 public:
22 char number;
23 int number1;
24 };
25 int main(){
26 printf("A %d B %d\n",sizeof(A),sizeof(B));
27 getchar();
28 return 0;
29 }
got the answer:
As for why the second is 8, it is the memory alignment problem, refer to previous posts memory applications .
We found that the length of a class is its variable occupied space, that function is not to take up space. This is because when the object belongs to a class variable, and the function belongs to a class of this class.
So because of different objects and different virtual function what will happen?
We then look at the following two categories:
class A{
public:
virtual void func1(void){
printf("11111heihei\n");
};
void func2(void){
printf("11111heihei\n");
};
public:
int number;
};
class B{
public:
virtual void func1(void){
printf("heihei\n");
};
virtual void func2(void){
printf("heihei\n");
};
public:
int number1;
};
Output as a function of the following results were obtained:
1 #include <stdio.h>
2 class A{
3 public:
4 virtual void func1(void){
5 printf("11111heihei\n");
6 };
7 void func2(void){
8 printf("11111heihei\n");
9 };
10 public:
11 int number;
12 };
13 class B{
14 public:
15 virtual void func1(void){
16 printf("heihei\n");
17 };
18 virtual void func2(void){
19 printf("heihei\n");
20 };
21 public:
22 int number1;
23 };
24 int main(){
25 printf("A %d B %d\n",sizeof(A),sizeof(B));
26 getchar();
27 return 0;
28 }
We found that more than 4 bytes. This is because the virtual function assigned to a virtual function table vptr object, virtual function is called by the pointer. Class virtual functions therefore, will be more space for a pointer. But only a pointer is assigned. Such as the first function with vptr [1] is represented by the second vptr [2] is represented, and 0 is the index information table.
If wrong place, please correct me.
Reproduced in: https: //my.oschina.net/u/204616/blog/545402