Reputation: 65600
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
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
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