Page 1 of 1

Location in memory of class object and member objects (C++)

Posted: Wed Jun 18, 2014 8:10 pm
by beneficii
In C++, when you create a class object which has member objects, are there any guarantees that the first member object starts at the same location in memory as the class object itself and that the member objects will be consecutive (i.e. a member object that is not the first is guaranteed to follow immediately after the previous memory object)?

I'm asking this, because I want an object that is stored in a struct to be able to access other members of that struct simply by using pointer arithmetic, so I am wondering if it is feasible and, if it is, guaranteed in the C++ standard.

Re: Location in memory of class object and member objects (C

Posted: Thu Jun 19, 2014 12:29 am
by eranon
An object is an instance of class and a class is already a structure containing members (variables and functions). So, when you instantiate a class, you can keep a pointer toward it (the object) and if you want to keep track of several instances, you can (if you want) store these pointers in an array. Don't know if it reply to you question, but it's the way I understand it ^o^

Re: Location in memory of class object and member objects (C

Posted: Sat Nov 29, 2014 3:07 am
by coderdave
I know a pointer to a struct will work in the manner you describe (size, ordering as declared, etc..).

I honestly forgot about classes, but I kind of want to say "don't hold your breath." Somewhere in the recesses of my failing memory I recall classes doing their own thing. I think it has something to do with the function declarations as opposed to where their definitions are actually stored. Unless you are very certain exactly how many bytes your function declaration will take up, or that the optimizer didn't move things around, you're going to have to be cautious.