Re: parameter passing for virtual function
On 1 Jun., 17:18, Ethan <ethan.li...@gmail.com> wrote:
virtual void foo (std::string& s) { // do crap here; }
[...]
d.foo (name); // ok
d.foo ("another one"); // error
d.foo (string("another one")); // error
[...]
when call the virtual function with temporary variable as parameters,
it always says:
not matching function for call too 'Derived::foo(std::string)'
candidates are: virtual void Base::foo(std::string&)
This has nothing to do with the function being virtual.
is it because no reference created for temporary variable?
(in the 2nd and 3rd cases); I'd appreciate if someone can
give a detailed explanation on this.
thanks!
The C++ standard doesn't allow a reference to non-const bind to a
temporary object. This decision is usually explained with an example
like this:
void foo(long & x) {
x = 42;
}
int main() {
int i = 23;
foo(i);
cout << i;
}
The code above doesn't actually compile due to the "reference to non-
const can't bind to rvalues"-rule. But it would compile without it and
probably surprize the author when he/she checkts the program's result.
It would print 23 and not 42 because prior reference binding 'i' is
converted to a long which results in a temporary. This temporary is
modified inside foo and destructed afterwards. What you /can/ do is
something like this:
void say(std::string const& x) {
cout << x;
}
int main() {
say("hello World!"); // creates temporary string
}
A reference-to-const /can/ bind to temporaries. This really ought to
be in the C++ FAQ [1]. But I couldn't find it. At least it should be
covered by your C++ textbook.
Cheers!
SG
[1] C++ FAQ Lite http://www.parashift.com/c++-faq-lite/