Possible Duplicate:
Error on calling default constructor with empty set of brackets
When I run this I get the compiler warning:34 [Warning] the address of`Rational test4(), will always evaluate as true. but I am trying to make it so that the default constructor is the rational number 0/1. Line 34 is is int main() the line: cout << test4;.
#include <iostream>
using namespace std;
class Rational
{
public:
Rational();
friend ostream& operator <<(ostream& out,Rational rational1);
private:
int numerator;
int denominator;
};
int main()
{
//Rational test1(24,6), test2(24);
Rational test4();
//cout << test1<< endl;
//cout << test2<< endl;
cout << test4;
system("pause");
}
Rational::Rational() : numerator(0), denominator(1)
{
//empty body
}
ostream& operator <<(ostream& out,Rational rational1)
{
out << rational1.numerator <<"/"<<rational1.denominator;
return out;
}
The reason your program prints “1” is because
Rational test4();declares a function pointer. So how doesstd::coutprint a function pointer? It involves automatic conversions. First look to plain old data pointers. The I/O machinery does not have a mechanism for printing adouble*pointer, or aMyClass*pointer, or any of the myriad number of pointers that can arise. What the I/O machinery can do have is a mechanism to print avoid*pointer. Thanks to implicit conversions, that same mechanism works fordouble*andMyClass*pointers because all pointers convert tovoid*pointers.Function pointers don’t convert to
void*. Function pointers are not pointers! The only available conversion is to a boolean. That conversion to boolean is what let’s you do stuff likeif (function_pointer) do_something();Your function pointer isn’t null, so on conversion toboolit becomestrue, which prints as1.The solution is simple: Change that
Rational test4();toRationaltest4;`,