1. In C + + hollow structures and classes are 1 bytes, this 1 bytes is a special processing of the compiler. Otherwise, we'll consider the following procedure.
A;
A b;
cout<<&a<<endl;
cout<<&b<<endl;
Assuming that the empty struct and the empty class do not account for memory, then object A and object B must have the same address, and different objects have the same address, which is a very unreasonable logic.
So the compiler makes a special deal, classes and structs occupy at least one byte,
The other size of the class with the virtual function is at least 4 because the vptr is a pointer that takes up to 4 bytes.
classA
{
private:
int m_value;
public:
A(intvalue)
{
m_value=value;
}
void Print1()
{
printf("hello world");
}
void Print2()
{
printf("%d", m_value);
}
};
int main()
{
A*pA=NULL;
pA->Print1();
pA->Print2();
return 0;
}
2. This question examines the candidate's mastery of the C + + object model, in C + +, where member variables and member functions defined in a class are stored separately, all member functions are stored in code snippets, and member variables are stored on stacks or heaps.
Once you understand this object model, you know that member variables are not accessed in print1, so that you do not have access to the 0 address area reserved by the system, so there is no error, and the Print2 access member variable is accessed by the object model, which is the 0 address area, so the segment is wrong.
classA
{
private:
int m_value;
public:
A(intvalue)
{
m_value=value;
}
void Print1()
{
printf("hello world");
}
virtual void Print2()
{
printf("hello world");
}
};
int main()
{
A*pA=NULL;
pA->Print1();
pA->Print2();
return 0;
}
3. There is no valid object at the null address, so there is no valid vptr, so there will be a segment error when calling Print2, because according to the virtual function, the 4 bytes starting with NULL are not likely to point to the virtual function table. function calls made through these 4 bytes are only dead end.
From for notes (Wiz)
C + + class issues