ShoeMaker
ShoeMaker

Reputation: 139

Create class instance on stack

I am trying to play a little bit with memory in C++, I have defined myself a class and then I create an instance of that class inside of heap.

#include <iostream>

class mojeTrida {
  public:
  
  void TestPrint()
  {
    std::cout << "Ahoj 2\n";
  }
};

int main() {
  mojeTrida *testInstance = new mojeTrida();
  
  testInstance->TestPrint();
  
  std::cout << "Hello World!\n";
}

If I understand c++ correctly, anytime I am calling the keyword “new”, I am asking OS to give me certain amount of bytes to store a new instance of class inside of heap.

Is there any way I can store my class inside of stack?

Upvotes: 2

Views: 842

Answers (1)

Melebius
Melebius

Reputation: 6695

The way to create your object (i.e. class instance) on the stack is even simpler – local variables are stored on the stack.

int main() {
  mojeTrida testInstance;  // local variable is stored on the stack
  
  testInstance.TestPrint();
  
  std::cout << "Hello World!\n";
}

As you have noticed according to your comment, the operator . is used instead of -> when calling a method of the object. -> is only used with pointers to dereference them and access their members at the same time.

An example with a pointer to a local variable:

int main() {
  mojeTrida localInstance;  // object allocated on the stack
  mojeTrida *testInstance = &localInstance; // pointer to localInstance allocated on the stack
  
  testInstance->TestPrint();
  
  std::cout << "Hello World!\n";
  // localInstance & testInstance freed automatically when leaving the block
}

On the other hand, you should delete the object created on the heap using new:

int main() {
  mojeTrida *testInstance = new mojeTrida();  // the object allocated on the heap, pointer allocated on the stack
  
  testInstance->TestPrint();

  delete testInstance;  // the heap object can be freed here, not used anymore
  
  std::cout << "Hello World!\n";
}

See also: When should I use the new keyword in C++?

Upvotes: 10

Related Questions