why does this code throw an error

closed account (SECMoG1T)
Hi , am faced with a little bug here, I don't get why my compiler couldn't afford to convert the parameter in my constructor to a reference, instead it throws this error,please help me understand why, I will gladly appreciate your help


no match to function call foo::foo(std::string)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  class foo
   {
     public:
         foo (std::string &s1);
     private:
         std::string str;
   }

   foo::foo (std::string &s1) :str (s1) {}

   int main ()
   {
     std::string st ("hello");
     
     foo var(st); ///this works
     foo var1 (std::string(" hi ")); /// this throws an error. 
   }


Thanks in advance.
Last edited on
FYI you have a syntax error in your code you need a ';' at the end of your class

To answer your question you cant reference a temporary object unless its by const reference



This should work
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>


class foo
{
public:
	foo(const std::string &s1);
private:
	std::string str;
};

foo::foo(const std::string &s1) :str(s1) {}

int main()
{
	std::string st("hello");

	foo var(st); ///this works
	foo var1(std::string(" hi ")); /// this throws an error.


	std::cin.ignore();
	return 0;
}
closed account (SECMoG1T)
Absolutely correct it's workin now, thank you very much @Yanson for the insight, how I dint realize my
std::string ("hi"); was a temporal object, I definetly got no idea.
For the missing ',' , that was definitely a typo, probably am very weary by now and should have a little break.

Cheers man.
Topic archived. No new replies allowed.