C++ - Tips'n Tricks - Creating an object onto the stack and into the heap

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.

Explanation

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.

The code

Badprog.cpp

#include <iostream>

#include "Badprog.hh"

Badprog::Badprog(int &stackMe) {
    std::cout << "stackMe = " << stackMe << std::endl;
}

Badprog::~Badprog() {
}

Badprog.hh

#ifndef BADPROG_HH
#define    BADPROG_HH

class Badprog {
public:
    Badprog(int&);
    virtual ~Badprog();
private:

};

#endif

main.cpp

#include "Badprog.hh"

int main() {
    int stackVariable = 10;
    
    Badprog *hd = new Badprog(++stackVariable);
    delete hd;
    
    Badprog hd2 = ++stackVariable;

    return 0;
}

Compiling and running

g++ main.cpp Badprog.cpp -o gogogo ; ./gogogo

Ouput

stackMe = 11
stackMe = 12

Finally

You are now ready to create objects into the stack or into the heap.
It's up to you. laugh
 

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.