Louie Mazin
Louie Mazin

Reputation: 83

Heap vs Stack memory usage C++ for dynamically created classes

If you create a class in C++ with non-pointer member variables and non-pointer member functions yet you initialize an instance of the class dynamically (using pointers) does memory usage come from the heap or the stack?

Useful info for a project I am working on as I am trying to reduce memory from the stack :).

Any response is greatly appreciated.

Many thanks and happy coding.

Upvotes: 4

Views: 177

Answers (3)

Danvil
Danvil

Reputation: 22991

If you use operator new for allocating you class, than it is put on the heap. Not matter if member variables are accessed by pointers or not.

class A {
    int a;
    float* p;
};
A* pa = new A(); // required memory is put on the heap
A a; // required memory is put on the stack

But be careful as not every instance accessed by a pointer may actually be located on the heap. For example:

A a; // all members are on the stack
A* pa = &a; // accessed by pointer, but the contents are still not on the heap!

On the other side a class instance located on the stack may have most of its data on the heap:

class B {
public:
    std::vector<int> data; // vector uses heap storage!
    B() : data(100000) {}
};
B b; // b is on the stack, but most of the memory used by it is on the heap

Upvotes: 8

rajenpandit
rajenpandit

Reputation: 1361

for the pointer variable memory will be allocated in stack but when you are using new or malloc then that memory segment will be allocated in heap

Upvotes: 0

ScottMcP-MVP
ScottMcP-MVP

Reputation: 10415

If you use 'new' to create an object the object is created in the heap.

Upvotes: 1

Related Questions