Hey guys, I was wondering...

I always assumed that references were more or less constant "dereferenced" pointers.

With that in my mind I tried to do this:

#include <iostream>
#include <string>
using namespace std;

void outputIt(const string * const textz00rs){
    cout << *textz00rs << endl;
}

int main(){
    outputIt("window");
    return 0;
}

But that'll give me the error: cannot convert `const char*' to `const std::string*' for argument `1' to `void outputIt(const std::string*)' So I tried:

#include <iostream>
#include <string>
using namespace std;

void outputIt(const string &textz00rs){
    cout << textz00rs << endl;
}

int main(){
    outputIt("window");
    return 0;
}

And it works as planned! Where's the true difference between these two pieces of code? The compiler knows just as much in both cases, right?

Thanks in advance,
Nick

I'm curious why you expected a pointer to const char to be successfully converted to a pointer to std::string. The two are not compatible pointer types. The second example works because the string literal is used as a constructor argument in generating a temporary std::string object.

I thought a reference was basically a constant pointer, so that's why I thought I could replace any occurrence of "&" with "* const" and vice versa, but I was wrong. Coming from C I'm always wondering when to use references (they're strange and new and owell) and when just to stick with the somehow trusted concept of pointers...

Several minutes later

This article seems to explain the issue pretty well for me. References are pretty neat, but a bit hard to know when to use them and when not to. I'm sticking with "most of the time, use references" for now. When I don't want it to change the object itself I should just declare it a const.

You're getting an error from a completely different issue, it's not a pointers versus references problem, it's a complete type mismatch. const char*, which is basically the type you get with a string literal, is clearly incompatible with a std::string*. So when you try to pass a const char* to a function that expects a std::string*, the compiler rightly complains.

It's generally more difficult to wrap your head around concepts when you let other fundamental misunderstandings get in the way during experimentation.

This article has been dead for over six months. Start a new discussion instead.