Dynamic Memory and the Free Store

Allocating memory in constructors

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

Abstract art representing computer programming

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.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved