Paul Wicks
Paul Wicks

Reputation: 65600

How do I convert something of "string*" to "const string&" in C++?

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?

Upvotes: 1

Views: 9087

Answers (3)

Dolphin
Dolphin

Reputation: 4772

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

Upvotes: 2

RichieHindle
RichieHindle

Reputation: 281765

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.

Upvotes: 4

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422162

Change it to:

bar(*s);

Upvotes: 12

Related Questions