views:

314

answers:

3

For example, if I have the following:

void foo(string* s)
{
    bar(s); // this line fails to compile, invalid init. error
}

void bar(const string& cs)
{
    // stuff happens here
}

What conversions do I need to make to have the call the bar succeed?

+10  A: 

Change it to:

bar(*s);
Mehrdad Afshari
+4  A: 
void foo(string* s)
{
    bar(*s);
}

s points to a string, and bar requires a (reference to a) string, so you need to give bar what s points to. The way you spell "what s points to" is *s.

RichieHindle
+1  A: 

When converting a pointer to a reference it is important to make sure that you are not trying to convert a NULL pointer. The compiler has to allow you to do the conversion (because in general it can't tell if it is a valid reference).

void foo(string* s)
{
    if(0 != s){
      bar(*s);
    }
}

The * operator is the inverse of the & operator. To convert from a reference to a pointer your use & (address of). To convert a pointer to a reference use * (contents of).

Dolphin