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
        MyString(const char *inString);
        void print();
        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");
    return 0;


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


    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.


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

Related Questions

Sponsored Content

2 Answered Questions

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

10 Answered Questions

28 Answered Questions

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

26 Answered Questions

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

40 Answered Questions

6 Answered Questions

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

21 Answered Questions

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

5 Answered Questions

Sponsored Content