Stack and heap enable data management inside the memory.
But some data are added onto the stack and the other into the heap.
For the stack, there is a stack pointer that enables to catch the last data added onto the stack.
It means that the last data added will be the first used by the program. We call that a LIFO (last in, first out) system.
For the heap, this is quite different. Indeed, data added into the heap are added randomly in the RAM by the OS.
Data in the stack are lost at the end of a statement (if, else, for, while, etc.) and those into the heap are always accesible until we decide to delete them.
Let's see examples of creating an object onto the stack and into the heap.
In the following code, we are going to pass a variable to the constructor.
The first will be by allocating memory into the heap with the "hd" instance.
The second will be by without allocating memory into the heap but by adding a new variable into the stack, this is why we do with the "hd2" instance.
#include <iostream> #include "Badprog.hh" Badprog::Badprog(int &stackMe) { std::cout << "stackMe = " << stackMe << std::endl; } Badprog::~Badprog() { }
#ifndef BADPROG_HH #define BADPROG_HH class Badprog { public: Badprog(int&); virtual ~Badprog(); private: }; #endif
#include "Badprog.hh" int main() { int stackVariable = 10; Badprog *hd = new Badprog(++stackVariable); delete hd; Badprog hd2 = ++stackVariable; return 0; }
g++ main.cpp Badprog.cpp -o gogogo ; ./gogogo
stackMe = 11 stackMe = 12
You are now ready to create objects into the stack or into the heap.
It's up to you.
Add new comment