-
object in bool context
Well ... first please see this example using C++ ifstream:
Code:
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char** argv)
{
if (argc != 2)
{
cout << "Please give a file name." << endl;
return 1;
}
ifstream in(argv[1]);
if (in)
{
cout << "Success!" << endl;
in.close();
}
if (!in)
{
cout << "Failure!" << endl;
return 2;
}
return 0;
}
My question is how does ifstream object behave like a bool value in above code?
I want to write my own class. And I wish it's objects would behave in the same way.
Can you please tell me how can I write such a class?
-
There are several ways of doing this, but some ways are better than others. This article explains the differences between the different methods, and why some are better than others.
-
Oh My GOD!
I didn't even know about Code:
operator bool() { ... }
:shock:
And I experimented with Code:
operator int() { ... }
This also worked fine.
Wow! Thanks!
-
Wow!
All of this works fine! And I never knew it!
Code:
#include <iostream>
using namespace std;
class Cool
{
bool bval;
int ival;
const char* pval;
public:
operator bool() { return bval; }
operator int() { return ival; }
operator const char*() { return pval; }
Cool& operator =(bool b) { bval = b; return *this; }
Cool& operator =(int i) { ival = i; return *this; }
Cool& operator =(const char* p) { pval = p; return *this; }
};
int main(int argc, char** argv)
{
Cool val;
val = false;
cout << boolalpha << static_cast<bool>(val) << endl;
val = 55555;
cout << static_cast<int>(val) << endl;
val = "Amazing!";
cout << static_cast<const char*>(val) << endl;
return 0;
}
-
No, no, no! No abuse of implicit conversion. It leads to horrible code.
-
Ok CornedBee.
I was just excited about this new (for me) feature of C++ :D
I will not abuse this feature. I was just testing ...