We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,983 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Function, implicit value

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

3
Contributors
3
Replies
44 Minutes
Discussion Span
11 Months Ago
Last Updated
4
Views
OrangeTree
Newbie Poster
9 posts since May 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 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

NathanOliver
Posting Virtuoso
1,515 posts since Apr 2009
Reputation Points: 281
Solved Threads: 277
Skill Endorsements: 3

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
}
deceptikon
Challenge Accepted
Administrator
3,445 posts since Jan 2012
Reputation Points: 822
Solved Threads: 473
Skill Endorsements: 57

Thank you :). Yes, one little const.

OrangeTree
Newbie Poster
9 posts since May 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.1213 seconds using 2.68MB