Reputation: 33
I've got one general question, why can't I pass the the pointer's address as a reference?
void domdom(string &foo)
{
foo = "";
}
string fooso = "blabal";
string* p_fooso = fooso;
domdom(p_fooso); // <-- why is that not possible? And what should I pass to be able to modify foosoo?
I know I could change the function domdom
to accept (string* foo)
, but is it also possible to modify the string fooso
in the function by using the pointer to it and the given function?
Upvotes: 3
Views: 69
Reputation: 155046
Pointers and references are similar under the hood, but are used differently, which is why mixing them by implicit conversion is not allowed by C++, to avoid confusion.
However you can always explicitly convert a reference to a pointer, and vice versa, without incurring the overhead of a copy. For example, if you call the function as domdom(*p_fooso)
, you will get the desired effect, i.e. the function will receive reference to the exact object you'd get by dereferencing the pointer.
Upvotes: 1
Reputation: 2107
Just declare p_fooso as a string reference type. You might want to rename variable as r_fooso!
string& r_fooso=fooso;
Upvotes: 2
Reputation: 42838
why can't i pass the the pointer's address as a reference?
Because that's how the language is defined.
Instead, you can dereference the pointer to get a reference to the string:
domdom(*p_fooso);
or, pass the actual object directly:
domdom(fooso);
Also note that string* p_fooso = fooso;
doesn't compile. You have to write string* p_fooso = &fooso;
.
Upvotes: 6