MC logo

Function Overloading (Answer)

  Practice Questions

  1. Two different C++ functions may share the name when there is some difference in the number or type of their parameters. They may or may have different return types, but there must be a difference the parameter lists; the functions cannot be distinguished by return type.
    #include <iostream.h>

    void fred(char *msg, int cnt = 3, char *post = "!")
            cout << msg;
            while(cnt--) cout << post;
            cout << endl;
    void fred(char *msg, char *post)
            fred(msg, 3, post);

  2. fred("Hi"); prints Hi!!!, using the first version of fred with default values for cnt and post.

  3. fred("Huh", "?"); prints Huh???, using the second version of fred. It does not use the first version, because that requires integer, rather than a character pointer, as the second argument.

  4. fred("Never", 10); prints Never!!!!!!!!!!, using the first version of fred with the default value for post.

  5. fred("Arrrggggg", 5, "h"); prints Arrrggggghhhhh, using the first version of fred with no default parameter values.

  6. fred is not a recursive function because the second fred calls the first fred, not itself.

  7. fred(msg, , post); is a syntax error. Once you let a parameter default, you must let all the rest default as well.

  8. With void fred(char *msg, char *post = "!") and and the original
    void fred(char *msg, int cnt = 3, char *post = "!"), the call fred("Hi"); becomes ambiguous, hence a compile-time error.

  9. This would not help much because the declaration
    void fred(char *msg, int cnt = 3, char *post) is a compile-time error. When you provide a default for a parameter, you must also provide one for all parameters to the right.

<<Access Control Question Operator Overloading>>