0

In my header file, I have this:

std::string StringExtend(const std::string Source, const unsigned int Length, const bool Reverse); std::string StringExtend(const std::string Source, const unsigned int Length); 

In my cpp file, I have this:

std::string Cranberry::StringExtend(const std::string Source, const unsigned int Length, const bool Reverse) { unsigned int StartIndex = (Source.length() - 1) * Reverse; short int Increment = 1 - (Reverse * 2); int Index = StartIndex; std::string Result; while (Result.length() < Length) { if (Reverse) Result = Source.at(Index) + Result; else Result += Source.at(Index); Index += Increment; if (!InRange(Index, 0, Source.length() - 1)) Index = StartIndex; } return Result; } std::string Cranberry::StringExtend(const std::string Source, const unsigned int Length) { return StringExtend(Source, Length, false); } 

As you can see, the second form of the function is the exact same thing with the Reverse argument omitted. Is there a way to condense this, or do I have to have a function prototype and definition for each form?

3 Answers 3

7

Use a default parameter for your Reverse parameter.

std::string StringExtend(const std::string & Source, unsigned int Length, bool Reverse = false);

Get rid of the second function:

std::string StringExtend(const std::string & Source, unsigned int Length);

Sign up to request clarification or add additional context in comments.

Comments

2

You could set a default value for the "optional" parameter, like const bool Reverse = false.

2 Comments

Does that eliminate the second definition, the second prototype, or both?
It eliminates both the second prototype and its definition as well. In this case, you would only have one function (thus one prototype and one definition). Be aware that you define the default value for the optional parameter only for the prototype in the header file.
1

Yes use default argument for bool parameter. For example std::string StringExtend(const std::string Source, const unsigned int Length, const bool Reverse = false); Then there is no need of 2nd function

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.