4

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.

trincot
  • 317,000
  • 35
  • 244
  • 286
nahpr
  • 619
  • 7
  • 15
  • dup: http://stackoverflow.com/questions/11343015/where-does-the-member-variable-inside-a-class-allocated – PiotrNycz Oct 10 '12 at 20:15
  • Possible duplicate of [Class members and explicit stack/heap allocation](https://stackoverflow.com/questions/10836591/class-members-and-explicit-stack-heap-allocation) – underscore_d Nov 12 '17 at 14:50

2 Answers2

4

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

struct A
{
    int x;
    double yarr[20];
};

each A you will create will contain an integer and an array of 20 doubles... for example its size in bytes will be sizeof(int)+20*sizeof(double) and possibly more for alignment reasons.

When you allocate an object A on the heap all those bytes will be in the heap, when you create an instace of A on 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:

struct B
{
   int x;
   double *yarr;
};

In this case the structure B contains an integer and a pointer to an array of doubles and the size in memory for B is sizeof(int)+sizeof(double *) and possibly a little more. When you allocate an instance of B the constructor will decide where the memory pointed by yarr is going to be allocated from.

The standard class std::vector for example is quite small (normally just three pointers), and keeps all the elements on the heap.

6502
  • 112,025
  • 15
  • 165
  • 265
3

You will get one allocation on the heap that contains x and y. A is just a nice way to refer to that object.

I wish I could easily draw on Stack Overflow, but you can think of it something like this (very small) heap example:

        +-------------------------------+
        |            Heap               | 
        +-------------------------------+
        | Other memory here ...         | 
        +-------+-----------------------+
A *a -> | x | y | Other memory here ... |
        +-------+-----------------------+
Brendan Long
  • 53,280
  • 21
  • 146
  • 188