Fix the program
Some datatypes can be implicitly cast to others. This means that a specific overload for each function isn't always required. This saves you from having to create another function overload. However, in cases like this, it causes the program to output inaccurate information.
This program prints data with the datatype information.
The variable passed to print_data is a double, yet because a double can be cast to a float, and there is no dedicated print_data function with parameter type double, the program prints the value as a float.
#include <iostream>
void print_data(float data)
{
std::cout << "Float: " << data << "\n";
}
int main()
{
double variable = 3.14;
print_data(variable);
float variable2 = 3.14f;
print_data(variable2);
}
Float: 3.14
Float: 3.14
Preffered Output:
Double: 3.14
Float: 3.14
Answer
#include <iostream>
void print_data(float data)
{
std::cout << "Float: " << data << "\n";
}
void print_data(double data)
{
std::cout << "Double: " << data << "\n";
}
int main()
{
double variable = 3.14;
print_data(variable);
float variable2 = 3.14f;
print_data(variable2);
}
Information-nugget:
The compiler tries matching the argument types with the parameter types.
It looks for a function that can be called by implicitly converting the argument if it can't find a perfect match.
In this case, calling print_data(int(1)); on the tasks code will compile.
It will be implicitly cast to a float, and then run as if it is a float.
However, when you introduce function overloading, as done in the answer of this task, there's an ambiguity.
The compiler won't know if you want it to use void print_data(double) or void print_data(float).
Because of this print_data(int(1)) won't compile if inserted into the code provided in the answer.
You have to cast it to double or float for it to compile.