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 :).

Recommended Answers

All 3 Replies

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

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
}

Thank you :). Yes, one little const.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.