0

Hi

I have a small question, probably quite obvious but I cant seem to figure it out.
When using the ifstream or any other stream you can tell if it was sucessfull in its last event. For example:

#include<fstream>
int main() {
	ifstream in("test.txt", ios::in);
	if (in) {
	} // Load successful
	else {
	} // Load fail
	return 0;
}

I understand why this works as if it doesn't load successfully, the variable in will be pointed to NULL. But when trying to copy this example I coulden't figure out how to do this. For example:

#include<iostream>
#include<fstream>
using namespace std;

class Example {
private:
public:
	Example() {
	};
	void Change() {
		// this = ((void*)0); // doesnt work
	}
};


int main() {
	Example example;

	if (example) cout << "Worked\n";
	} else       cout << "Didnt work\n";

	example.Change();

	if (example) cout << "Worked\n";
	} else       cout << "Didnt work\n";

	cin.ignore();
	return 0;
}

Does anybody else know how?

2
Contributors
2
Replies
4
Views
9 Years
Discussion Span
Last Post by William Hemsworth
1

I guess you are after this

class test
{
    bool is_good;

public:
    test() : is_good(true){}

    operator void * ()
    {
        if(is_good)
            return (void*)this;
        else
            return 0;
    }

    void go_bad()
    {
        is_good = false;
    }
};

int main()
{
    test t;

    if(t)
        cout << "good\n";
    else
        cout << "bad\n";

    // change the state ...
    t.go_bad();

    if(t)
        cout << "good\n";
    else
        cout << "bad\n";

    return 0;
}
Votes + Comments
Great simple answer. Thanks :)
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.