Re: Memory layout of class
On Jun 29, 10:52am, Peskov Dmitry <vamsi.kom...@gmail.com> wrote:
> Hi,
> What is the memory layout of an object, and the derived object.
> For example :
>
> class A
> {
> private:
> int prv_data;
> protected:
> int pro_data;
> public:
> int pub_data;
> A(){prv_data = 10;}
> void Aprint();
>
> };
>
> class B : public A
> {
> int pro_data;
> public:
> void Bmember1();
> void Bprint();
>
> };
>
> Does it depend on the compiler ?
>
> int main()
> {
> B b;
> int *ptr;
>
> ptr = (int *)&b;
> *ptr = 1000;
> ptr++;
> *ptr = 2000;
> ptr++;
> *ptr = 3000;
> ptr++;
> *ptr = 4000;
>
> return 0;
>
> }
>
> is setting only the private element of class A to 1000, rest are not
> being set.
You can inspect the memory layout of a class by breaking in the
debugger, then taking the address of the object (b in your case) and
reading the contents of the memory from that location onwards.
I ran your above code in Visual Studio 2008 (except assigning ptr to
&b and incrementing the pointer etc). I assigned 10, 20 and 30 to
pri_data, pro_data, and pub_data respectively so that I can easily
identify them when I read the memory.
Here's what I found:
1. The memory contained pri_data first, pro_data second and the third
was pub_data. This is because you declare them in that order. Reverse
the order and you will find the memory is laid out as pub_data,
pro_data and pri_data.
Don't know if this is required by C++ std. or the compiler does it
this way. Also it is a good practice to initialize member variables in
the constructor in the order in which they are declared in the class
declaration. (from Scott Meyers book Effective C++: 50 specific ways
to improve your program and design, 2nd. edition).
2. Contents of the inherited class B come after A.
Hope that s.
|