Search code examples
c++initializationnew-operator

How do I assign an initial value to a dynamic variable without using assignment operator?


I am creating a dynamic variable in the heap via a pointer.

int* p = new int;

I'm sure we're all familiar with that. However, I want to create the dynamic variable and give it an initial value all in one step! I do not want to later use the assignment operator.

*p = 5;

I want all of my dynamic variables to have the same initial value, avoiding the extra overhead of the assignment operator.

How would you do this if the dynamic variable were a class instead of an int? I know that it's possible to create and initialize a class variable of the stack in one step:

class Dog {...};

Dog d1("Spot", 5);

Can you do the same if the Dog object were a dynamic one instead? My program needs to dynamically allocate and initialize variables of both POD and class types.


Solution

  • Yes you can, direct initialization supports it. Just specify the initializer.

    initialization of an object with dynamic storage duration by a new-expression with a non-empty initializer

    int* p = new int(5);
    Dog* d1 = new Dog("Spot", 5);