Allocating memory in constructors

Is it okay to use new inside a constructor to allocate memory for my class?

Yes, it's perfectly fine and common to allocate memory using new inside a constructor. This is often necessary when the amount of memory needed is not known at compile time.

Here's an example:

#include <iostream>

class MyClass {
private:
  int* data;
  size_t size;

public:
  MyClass(size_t size) : size(size) {
    data = new int[size];
  }

  ~MyClass() {
    delete[] data;
  }
};

int main() {
  MyClass obj(10);
}

However, there are a few important things to keep in mind:

  1. If you allocate memory in the constructor, you must deallocate it in the destructor to avoid memory leaks.
  2. If your constructor can throw exceptions, you need to be careful. If an exception is thrown after you've allocated memory but before the constructor completes, your destructor won't be called. This can lead to memory leaks. One solution is to use smart pointers, which we'll cover in a future lesson.
  3. Allocating memory in the constructor can make your class more difficult to reason about and maintain. Where possible, consider using standard library containers like std::vector instead of managing memory manually.

Dynamic Memory and the Free Store

Learn about dynamic memory in C++, and how to allocate objects to it using new and delete

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Should I delete this?
Since I am responsible for memory allocated with new, should I delete this from within my class destructor?
When to use the stack vs the heap
How do I decide when to allocate memory on the stack versus the heap?
Identifying Memory Leaks
How can I tell if my C++ program has a memory leak?
Returning from multiple points
What if my function needs to return from multiple points? How can I ensure all allocated memory is freed?
Writing a memory manager
Can I write my own memory manager to replace new and delete?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant