Search code examples
c++arraysstringopenframeworksfunction-parameter

initializing an passing a string array as a parameter


Can I initiate a string array and pass it as a function that initializes it. I know this sounds redundant, but basically I want to initiate a string array and then pass it to a variable so that I can use it later? Something like this:

This is the .h:

class ScreenBasics{

 void setupAnswers(int &_numberOfAnswers, string *_answersText);

 string *answersText;


{

This will be the implementation .cpp

void ScreenBasics::setupAnswers(int &_numberOfAnswers, string *_answersText){

 answersText = _answersText; // this is where I get confused cause I don't know if I should initiate my string pointer using new like answersText = new string(_numberOfAnswers);

{

so in the main.cpp I can do something like this:

 int main( ) {

 ScreenBasics basics;
 int numberOfAnswers = 4;
 string newAnswers [] = { "Good", "Superb", "Great", "Perfect"};
 basics.setupAnswers(numberOfAnswers, newAnswers);

 // let's say I want to call some of those answers later
 for ( int i = 0; i < numberOfAnswers; i++){

  cout << basics.answersText[i] << endl;

 }

}

Thanks!


Solution

  • It sounds like your class should use a constructor to initialize the pointer.

    class ScreenBasics
    {
        ScreenBasics(std::string* _answersText, std::size_t size)
            : answersText(new std::string[size])
        {
            // copy values from _answersText to answersText
        }
    };
    

    Note that since you are allocating a resource dynamically, you will need to implement The Rule of Three: that is, you need to create a copy-constructor, copy-assignment operator and destructor. This is because their default implementations do not semantocally conform to our requirements. For instance, the default copy-constructor and copy-assignment operator perform shallow copies (that is, they copy the pointer but not what it points to). Also, the destructor doesn't free the memory allocated my new[]. You will need to provide your own definition of the destructor that calls delete[].

    Fortunately, all this can be avoided by using the standard library container std::vector, which is a dynamic array class that handles the memory allocation for you. The default implementations of the aforementioned constructors will correctly copy/copy-assign a vector if the need be:

    class ScreenBasics
    {
        ScreenBasics(std:vector<std::string> _answersText)
            : answersText(_answersText)
        {
        }
    };
    

    Notice that the size also didn't have to be passed as a parameter. A vector maintains its size internally.