In C++, what is the difference in making member variables values or pointers? For example, what is the difference between pThread and thread in the following code:
class A {
public:
boost::thread *pThread;
boost::thread thread;
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The difference is the memory layout of the object.
Member items are stored like a struct – sequentially and continuously stored in the memory (possibly with 2-4-8 bytes alignment but otherwise sequentially one after the other). Pointers are stored in the memory address as a 4/8 byte pointer while the actual object can be stored anywhere in the memory.
Consider the situation where you have a struct
The size of the struct is 7 bytes.
Now if you have a class Student_member:
and a class Student_pointer:
Then the size in memory of the class Student_member would be 4+7=11 bytes (long + the struct) which would be allocated as a continuous block, while the size in memory of class Student_pointer would be 4+4=8 byte (long + pointer) and another 7 bytes that are allocated somewhere else in memory storing the actual grades.