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?

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;
}
commented: Great simple answer. Thanks :) +2

That is what im after :) thanks, didn't know that was possible.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.