parameter passing for virtual function

E

Ethan

class Base {
public:
virtual void foo (std::string& s) { // do crap here; }
};

class Derived : public Base {
// other crap
};

int main() {
Derived d;
std::string name("anyone");

d.foo (name); // ok

d.foo ("another one"); // error
d.foo (string("another one")); // error
}



g++ 3.4.6

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

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!
 
S

SG

   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/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top