1

In the code below, the function getName() returns a char *. I would of thought that it should (it also can) return a string. How does cout correctly print it to the console if it is just a pointer to the first char?

#include <iostream>
#include <string>

using namespace std;

class Base
{
protected:
    int m_value;

public:
    Base(int value)
        : m_value(value)
    {
    }

    const char* getName() { return "Base"; }
    //string getName() { return "Base"; }
    int getValue() { return m_value; }
};


int main()
{
    Base base(5);
    std::cout << "Base is a " << base.getName() << " and has value " << base.getValue() << '\n';


    return 0;
}
arcoxia tom
  • 1,531
  • 4
  • 14
  • 25
  • 1
    Allow me to refer you to our selection of [book recommendations...](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – StoryTeller - Unslander Monica Apr 04 '18 at 09:34
  • Consider learning from a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). C-strings (a.k.a. null-terminated strings) are delimited with `\0` character. `std::cout` just keeps printing it, until it reaches such a character. – Algirdas Preidžius Apr 04 '18 at 09:34
  • Because the string literals have an implicit null terminator in them. So when sent to the output stream it knows when to stop sort of speaking. – Ron Apr 04 '18 at 09:35
  • 2
    There is a special `operator<<` overload for `const char*` that displays the string instead of just the pointer. – Bo Persson Apr 04 '18 at 09:35
  • 1
    There is an `operator<<()` function or method which takes the pointer as a parameter and iterates over it until it finds a null character and stops. This is just like `printf()`. – quamrana Apr 04 '18 at 09:35
  • The `const char *` parameter is a *copy* of the pointer returned by `getName`. It can be incremented, independent of `Base`, and dereferenced. The implementation might look something like `for ( ;*str; ++str) { stream.put(*str); }` – Caleth Apr 04 '18 at 09:56

1 Answers1

2

cout and friends consider the type char * to be a C-string.

If you want it to print a single character referred by a pointer, you have to dereference it first, so cout gets the char type. Or, since a C-string is an array of chars, you can use its 0th item.

const char* myString = "Hello";
cout << "string:    " << myString << endl
     << "*string:   " << *myString << endl
     << "string[0]: " << myString[0] << endl;

gives (check it online):

string:    Hello
*string:   H
string[0]: H
Melebius
  • 6,183
  • 4
  • 39
  • 52