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

This forum is reserved for everything you want to talk about. It could be about programming, opinions, open source programs, development in general, or just cool stuff to share!
Post Reply
beneficii
Earned some good credits
Earned some good credits
Posts: 111
Joined: Fri Nov 27, 2009 2:49 am

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

Post 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.
User avatar
eranon
Can't get richer than this
Can't get richer than this
Posts: 867
Joined: Sun May 13, 2012 11:42 pm
Location: France
Contact:

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

Post 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^
[Ind. dev. - wxWidgets 3.0/3.1 under "Win 7 64-bit, TDM64-GCC" + "OS X 10.9, LLVM Clang"]
coderdave
In need of some credit
In need of some credit
Posts: 3
Joined: Sat Nov 29, 2014 12:36 am

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

Post 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.
Post Reply