Search code examples
c++objectpointersdynamicconstructor-overloading

How to pass value to the object constructor's declare using dynamic memory allocation


The code is as follow :

The Code :

#include <iostream>

using namespace std;

class pub
{
    string name;

    public:
    pub(string name):name(name){}    //Constructor
    void getName(string name){this->name = name;}
    string returnName(void){return name;}
};

int main(void)
{
    pub * p = new pub[5]; //Error-prone statement.

                          //Ignore for not having "delete" statement

    return 0;
}

The Question :

1.) In this case , is there any method for me to pass value to each dynamic memory I've allocated , or is it I have to set a default value to the constructor's argument in order to circumvent this problem ?

Thank you !


Solution

  • If your compiler supports C++11 you could use std::vector and with an initializer list:

    std::vector<pub> v { pub("1"), pub("2") };
    

    See online demo https://ideone.com/Qp4uo .

    Or std::array:

    std::array<pub, 2> v = { { pub("1"), pub("2") } };
    

    See online demo https://ideone.com/lBXUS .

    Either of these also removes the burden of delete[]ing the dynamically allocated array.