Let’s say I have:
class A{
public:
int x;
int y;
};
And I allocate an A instance like:
A *a = new A();
Does a.x and a.y are also allocated in the heap, since they are ‘dependent’ of a heap allocated object?
Thank you.
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.
It is important to understand that C++ uses “copy semantic”. This means that variables and structure fields do not contain references to values, but the values themselves.
When you declare
each
Ayou will create will contain an integer and an array of 20 doubles… for example its size in bytes will besizeof(int)+20*sizeof(double)and possibly more for alignment reasons.When you allocate an object
Aon the heap all those bytes will be in the heap, when you create an instace ofAon the stack then all of those bytes will be on the stack.Of course a structure can contain also a pointer to something else, and in this case the pointed memory may be somewhere else… for example:
In this case the structure
Bcontains an integer and a pointer to an array of doubles and the size in memory forBissizeof(int)+sizeof(double *)and possibly a little more.When you allocate an instance of
Bthe constructor will decide where the memory pointed byyarris going to be allocated from.The standard class
std::vectorfor example is quite small (normally just three pointers), and keeps all the elements on the heap.