0

I have an existing function, and I'd like to add a parameter and set a default value for it so it won't affect other modules that use it.

BOOL myFunc(int A, CString& strTest);

Initializing it to NULL or 0 gives me an error message. How do I initialize strTest in my func declaration?

Owen
  • 4,063
  • 17
  • 58
  • 78

2 Answers2

2

Probably initialize it to an empty string:

CString dummy = "";

BOOL myFunc(int A, CString &strTest=dummy);

If you're allowing a default value, you probably want to make it a reference to a const string though:

BOOL myFunc(int A, CString const &strTest = dummy);

You might want to consider using overloading instead though -- leave the existing function exactly as it is (no extra parameter), and write a second function (that may forward to the first) that takes the extra parameter:

BOOL myFunc(int A);
BOOL myFUNC(int A, CString const &strTest);
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • when I assign a value to strTest inside myFunc, it says Error 1 error C2678: binary '=' : no operator found which takes a left-hand operand of type 'const CString' (or there is no acceptable conversion) – Owen Feb 22 '13 at 07:15
  • @Owen: right -- if you make it const, you can't assign to it. If the user hasn't passed anything, where do you expect your assignment to go? I think you need to clarify what you want to accomplish -- trying to modify something that may not have been passed doesn't seem to make much sense. – Jerry Coffin Feb 22 '13 at 07:17
  • inside myFunc() another function passes a string. I would like to assign that string to myFunc's strTest. Can I use const_cast ? – Owen Feb 22 '13 at 07:22
  • @Owen: Are you expecting what you assign to become visible to the caller of `myFunc`, or are you just using `strTest` as a local variable, so modifying it only changes what's visible locally? – Jerry Coffin Feb 22 '13 at 07:24
  • I'm expecting your first point... "expecting what you assign to become visible to the caller of myFunc" – Owen Feb 22 '13 at 07:36
  • I just figured another way. Instead of passing by reference, I used CString pointer and later dereference it. – Owen Feb 22 '13 at 10:26
1

You may try in this way

A.h

class A{
    public:
      static CString defArg;
      bool myFunc(int A, CString& strTest=defArg);
 };

A.cpp

CString A::defArg = "defArg";

bool myFunc(int A, CString& strTest){
 //what you need to do
}
Nayana Adassuriya
  • 23,596
  • 30
  • 104
  • 147