By user637965


2011-10-17 01:38:01 8 Comments

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;
}

3 comments

@Mysticial 2011-10-17 01:40:10

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*.

@redache 2011-10-17 01:44:25

This is down to the fact that "<<" will automatically follow the pointer and print out the string instead of just printing out the memory address. This is easier to see in printf as you can specify the print out of a pointer OR what the pointer references.

#include <stdio.h>
#include <stdlib.h>

int main(int argc,char** argv)
{
    char string1[] = "lololololol";
    char* string2;

    string2 = string1;

    printf("%s",string2);
    printf("%p",string2);

    return EXIT_SUCCESS;
}

You can see here that %s prints out the string and %p prints out the memory address.

@Tanveer Badar 2019-07-13 05:49:15

But only for char* and wchar_t* types, not any and all pointers.

@Greg Hewgill 2011-10-17 01:41:01

The variable pString is a pointer. However, the implementation of << when used with an output stream knows that if you try to output a char *, then the output should be printed as a null-terminated string.

Try:

cout << static_cast<void *>(pString);

Related Questions

Sponsored Content

27 Answered Questions

[SOLVED] Easiest way to convert int to string in C++

5 Answered Questions

25 Answered Questions

[SOLVED] Why do we need virtual functions in C++?

37 Answered Questions

21 Answered Questions

[SOLVED] Why should I use a pointer rather than the object itself?

  • 2014-03-03 11:54:16
  • gEdringer
  • 298715 View
  • 1535 Score
  • 21 Answer
  • Tags:   c++ pointers c++11

10 Answered Questions

3 Answered Questions

[SOLVED] Why is 'this' a pointer and not a reference?

6 Answered Questions

[SOLVED] What does "dereferencing" a pointer mean?

1 Answered Questions

[SOLVED] Why does printing a char* give a string rather than an address?

Sponsored Content