-9
    #include<iostream>
    #include<string.h>
    using namespace std;

class MyString
{
private:
    char *m_pchString;
    int m_nLength;

public:
    MyString(const char *pchString="")          // explain this
    {
        m_nLength = strlen(pchString) + 1;

        m_pchString = new char[m_nLength];       // explain this

        strncpy(m_pchString, pchString, m_nLength);

        m_pchString[m_nLength-1] = '\0';
    }

    ~MyString()  
    {
        delete[] m_pchString;

        m_pchString = 0;
    }

    char* GetString() { return m_pchString; }    // explain this
    int GetLength() { return m_nLength; }
};


 int main()
 {
   MyString cMyName("Alex");
   cout << "My name is: " << cMyName.GetString() << endl;
   return 0;
 }

why is new operator used in this....i understood most of it but i am confused why a char pointer is allocated an array using new operator....? this is a C++ code.....

shaik
  • 1
  • 3

2 Answers2

1

The operator new (it is - in fact - the new[]-Operator) is used to obtain an Array of char with m_nLength elements. The delete[]-Operator in the destructor is used to free the memory.

urzeit
  • 2,863
  • 20
  • 36
  • 6
    And the [invalid copy semantics](http://stackoverflow.com/questions/4172722) are used to keep you entertained with long debugging sessions. – Mike Seymour Jun 19 '13 at 12:05
  • What @Mike Seymour wants to say is that it would be a really good idea to implement a copy constructor as well since a copy of an instance of `MyString` will use the same buffer as the original which may lead to unexpexted results. If you then destroy one of the objects you will most likely get a segfault when using the other one since the pointer will point to invalid memory (that is freed by the copy's destructor). – urzeit Jun 19 '13 at 13:19
  • And a copy assignment operator. And move versions of those. – chris Jun 19 '13 at 13:36
0
MyString(const char *pchString="") 

A Constructor of class MyString with an [optional] parameter that has type of char* so, MyString str; will be valid.

m_pchString = new char[m_nLength];

m_pchString is a raw pointer. In this implementation, it is pointing to garbage address(?) (not really sure 'cause in C++ compiler, pointers are not initialized to NULL). It needs to allocate first resources on heap. And dangerous to use if not handled properly.

char* GetString() { return m_pchString; }

It returns the base address of m_pchString so that you can have an access on the following address m_pchString's pointing to and stops when it finds 0.

mr5
  • 3,438
  • 3
  • 40
  • 57
  • Also note that the return value of GetString is not `const`. It will be possible to change the buffer outside of `MyString` which will contradict the idea of data capsulation. – urzeit Jun 19 '13 at 13:22