Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I declare a class instance on the heap are all its members going to be on the heap as well?

I was wondering if I declare a class instance on the heap (new) are its members going to be on the heap as well even if they weren’t created using the new keyword?

like image 374
Serket Avatar asked Sep 04 '25 16:09

Serket


2 Answers

Lets say that we declare a class like so:

class Foo
{
private:
    std::string Bar;
public:
    Foo(std::string Bar);
}

When you create a new object of that class, it's data members are saved on the same place as the object itself, meaning that if you do something like this Foo* f = new Foo("hello"); all of the data is stored in the heap, but if you do Foo f = Foo("hello"); it will be stored on the stack.

Why so? when you create an object of class like foo, it's data members are referred as sub-objects, and from the memory's perspective, the class object and it's sub-objects are one, meaning that if you create an object of foo on the heap, all of it's sub-objects will be stored on the heap as well as they are one with the class object itself. When you create an instance of a class, you don't get redirected to somewhere else when you try to access it's data members, you merely accessing a specific part within the object itself.

like image 63
Kidsm Avatar answered Sep 07 '25 16:09

Kidsm


Yes all member variables inside your class are continuous in memory. So if your class object is in heap (created with new) the object will use the memory up to sizeof(YourClass). The size depends on the individual size of all its non static members (some padding might be applied too).

class ExampleClass {
public:
    int first;
    float second;
};

void test() {
    ExampleClass *obj = new ExampleClass;

    std::cout << obj << " object address \n";
    std::cout << &obj->first << " first member address \n";
    std::cout << &obj->second << " second member address \n";

    delete obj;
}

Will print:
0x55c0f4c85eb0 object address
0x55c0f4c85eb0 first member address
0x55c0f4c85eb4 second member address 
like image 45
Knutz Avatar answered Sep 07 '25 18:09

Knutz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!