0

Hello :). How can I fix this?

Yes, I can write 2 functions (with and without parameter) ... but what is bad there?

#include <cstdlib>
#include <string>
#include <iostream>
using namespace std;

class CClass{
public:
   void foo(string & s = "default"); // COMPILE ERROR
   string backup;
};

void CClass::foo(string & s){
   backup = s;
}

int main(int argc, char const *argv[]){
   CClass myClass;

   cout << myClass.backup << endl;
   myClass.foo ();

   cout << myClass.backup << endl;
   string str = "amazing world";

   myClass.foo (str);
   cout << myClass.backup << endl;

   return 0;
}

Thanks :).

Edited by OrangeTree

3
Contributors
3
Replies
5
Views
5 Years
Discussion Span
Last Post by OrangeTree
0

I believe the problem lies in the fact that you only have 1 paramater in your function. From functions I have seen you need to have at least one paramater that does not have a default paramater

1

void foo(string & s = "default");

Make it a const reference:

void foo(string const& s = "default");

It's really no different from just calling a function taking a reference with a string literal:

#include <string>

using namespace std;

void foo(string&) {}

int main()
{
    foo("test"); // Error, "test" is an rvalue
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.