I am reviewing for my final, and I cannot figure out why this question is what it is.
Assume the following class declaration:
class Testing {
public:
Testing(int n);
void Show(const Testing& w, int a = 10);
int value;
private:
int DoThis();
};
Assume the following lines of code are attempting in a main() program, and that x is of type Testing and has been propertly created.
x.Show(18); Legal or Illegal
The answer is legal, I understand that the 2nd parameter is not needed because of the = 10,but since 18 is not of type Testing isn’t that an invalid parameter?
Testing has a non-
explicitconstructor that takes an int. Therefore, an int can be implicitely converted to aTestingby constructing a temporary object.Since Show takes a
const Testing &(and not just aTesting &), you can pass a temporary to it. Finally, the second parameter is optional, so you don’t have to specify a value for that.This whole mechanism is what allows you do this, by the way:
Here,
"Hello"is of typeconst char (&)[6], which decays to aconst char *, but you can construct astd::stringfrom aconst char *, thus permitting the use of aconst char *where astd::stringparameter is needed.Keep in mind that this constructs a temporary, and therefore is only valid for parameters that are passed by value or by const reference (it will fail for references). Also, the constructor must not be marked as
explicit.