#include <iostream> using namespace std; class Foo { public: Foo(): initialised(0) { cout << 'Foo() gets called AFTER test() ?!' << endl; }; Foo test() { cout << 'initialised= ' << initialised << ' ?! - '; cout << 'but I expect it to be 0 from the 'initialised(0)' initialiser on Foo()' << endl; cout << 'this method test() is clearly working on an uninitialised object ?!' << endl; return Foo(); } ~Foo() {}; private: int initialised; }; int main() { //SURE this is bad coding but it compiles and runs //I want my class to DETECT and THROW an error to prevent this type of coding //in other words how to catch it at run time and throw 'not initialised' or something Foo foo=foo.test(); }
#include <iostream> using namespace std; class Foo { public: Foo(): initialised(0) { cout <<
Share
You can’t prevent people from coding poorly, really. It works just like it ‘should’:
Just like it should. You can’t prevent people from not knowing the right way to use C++.
The best you could do is have a magic number:
This ‘works’ because the chances _magicFlag gets allocated where the value is already 1337 is low.
But really, don’t do this.