0

I am confused about this library code..

what is the purpose of writing pointer in attributes name? Like string *name;

this is the code:

    #include <iostream>
     using namespace std;
     class stringlist
     {
     private:
        int numstrings;
        string *strings;
     public:
        stringlist() : numstrings(0), strings(NULL)
        {}
        // copy constructor
        stringlist(const stringlist &other) :
           numstrings(other.numstrings),
           strings(new string[other.numstrings]) {
           for (int i=0; i<numstrings; i++) {
              strings[i] = other.strings[i];
           }
     }
        // destructor
        ~stringlist() {
           if (numstrings > 0) delete [] strings;
        }
        void printStrings();
        const string& getString(int num);
        void setString(int num,
                       const char *astring); 
     void setString(int num,
                 const string &astring);
     int getNumstrings() {
     return numstrings;
     }
     void setNumstrings(int num);
     void swapStrings(stringlist &other) ;
     // overloaded operators
     stringlist& operator =
               (const stringlist &other) {
     stringlist temp(other);
     swapStrings(temp);
     return *this;
     }
     };

Can anyone please explain what is the purpose of using string *strings instead of string strings?

Thanks all!

Rakib
  • 7,435
  • 7
  • 29
  • 45
AlbertSamuel
  • 584
  • 10
  • 33

2 Answers2

1
string *strings;

declares a pointer to the first element of an array of strings. Because of C/C++ array/pointer semantics, you can treat this as an array of strings, e.g. index it as strings[n] to get the nth element.

string strings;

would just be one string. Since the class is for holding a list of strings, declaring just one string would not be sufficient.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 3
    It doesn't. It's just a pointer to a string. It just so happens that the intended use is to point at the first element in an array. Yet another reason why pointers can be terribly ambiguous. – Joseph Mansfield Jun 19 '14 at 05:14
  • Look at the copy constructor, it initializes `strings(new string[other.numstrings])`. That's allocating an array. Other code that he hasn't shown would be similar to create a new `stringList`. – Barmar Jun 19 '14 at 05:33
  • 2
    Yes, which makes it point at the first element of an array. The declaration is not a pointer to array though. That would look like `string (*strings)[N]`. – Joseph Mansfield Jun 19 '14 at 05:36
0

In the code you gave, *strings is used for a dynamic array. You can see that it's allocated with strings(new string[other.numstrings]) and the destructor deletes it if it's pointing to something.

More on dynamic arrays: - http://www.cplusplus.com/doc/tutorial/dynamic/

Community
  • 1
  • 1
Unglued
  • 419
  • 6
  • 15