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:
std::vector
 instead of managing memory manually.Answers to questions are automatically generated and may not have been reviewed.
Learn about dynamic memory in C++, and how to allocate objects to it using new
and delete