Search code examples
c++pointersdynamic-arrays

Why does my pointer output a string and not a memory address in C++?


I'm working on a string class that employs pointers and I'm just having some difficulty in understanding how my print function works here. Specifically, why does cout << pString output the string and not the memory address of the dynamic array that it's pointing to? My understanding was that the variable pString was a pointer.

class MyString
{
    public:
        MyString(const char *inString);
        void print();
    private:
        char *pString;
};


MyString::MyString(const char *inString)
{
    pString = new char[strlen(inString) + 1];
    strcpy(pString, inString);
}

void MyString::print()
{
    cout << pString;
}

int main( )
{
    MyString stringy = MyString("hello");
    stringy.print();
    return 0;
}

Solution

  • This is because the << operator has been overloaded to handle the case of a char* and print it out as a string. As opposed to the address (which is the case with other pointers).

    I think it's safe to say that this is done for convenience - to make it easy to print out strings.

    So if you want to print out the address, you should cast the pointer to a void*.