I don't understand this or why he did it this way

357mag

Well-known member
Joined
Mar 31, 2023
Messages
82
Programming Experience
3-5
I know this is a C# forum but the C++ forum I have been to has some rude snobs on it. This is a code snippet from a project in one of my books on C++. The subject is function overloading. I understand completely the logic behind the first two functions. It makes sense to use a simple if-else statement. But in the third function, the author did it differently. And I can't figure out what it means:

C#:
int maximum(int num1, int num2)
{
    if(num1 > num2)
        return num1;
    else
        return num2;
}

double maximum(double num1, double num2)
{
    if(num1 > num2)
        return num1;
    else
        return num2;
}

double maximum(double num1, double num2, double num3)
{
    return maximum(max(num1, num2)num3);
}

I don't understand the return maximum(max(num1, num2)num3);

It's hard for me to read it also. What is happening in that final statement?
 
Looks like one of the many typos in the Schildt C++ book.

That should be something like:
C#:
double maximum(double num1, double num2, double num3)
{
    return maximum(maximum(num1, num2), num3);
}

which is effectively:
C#:
double maximum(double num1, double num2, double num3)
{
    double maxOfFirstTwo = maximum(num1, num2);    // call the version that takes two parameters
    return maximum(maxOfFirstTwo, num3);    // call the version that takes two parameters
}
 
The reason for the three parameter version calling the two parameter version is to follow the DRY Principle: Don't Repeat Yourself. Without calling the other two parameter version, you would end up with something like this:
C#:
double maximum(double num1, double num2, double num3)
{
    double maxOfFirstTwo;
    if (num1 > num2)
        maxOfFirstTwo = num1;
    else
        maxOfFirstTwo = num2;

    double maxOfAllThree;
    if (maxOfFirstTwo > num3)
        maxOfAllThree = maxOfFirstTwo;
    else
        maxOfAllThree = num3;

    return maxOfAllThree;
}

Notice that lines 3-7 is practically the same as lines 9-13.
 
No it wasn't Herb. This was out of Daniel Liang's book on C++.

Apparently, Daniel Liang's Java book is excellent, but his C++ book is still taught with C in mind first, rather than the modern C++ approaches first.
 
Back
Top Bottom