when run code attempts initialize array of objects, , 1 has invalid value, doesn't seem call constructor, set proper default value. code below produces output:
1 2 1528112104 toy code:
#include <iostream> using namespace std; class beeboop { public: static const int min_x = 1; static const int max_x = 2; beeboop(int x); int getx() { return x; } bool setx(int x); private: int x; }; int main() { beeboop boops[] = { beeboop(1), beeboop(2), beeboop(3) }; (int = 0; < 3; i++) cout << boops[i].getx() << endl; } beeboop::beeboop (int x) { if(!setx(x)) x = min_x; } bool beeboop::setx(int x) { if (x < min_x || x > max_x) return false; this->x = x; return true; } why isn't calling constructor , setting default beeboop(3)?
even weirder, if switch order of initialization list to
... beeboop boops[] = { beeboop(1), beeboop(3), beeboop(2) ) ... the output becomes:
1 0 2 so initializes 0, not default.
you're using name x both function parameter , member variable (probably not idea!). therefore need change:
beeboop::beeboop (int x) { if(!setx(x)) x = min_x; } to:
beeboop::beeboop (int x) { if(!setx(x)) this->x = min_x; } otherwise you're modifying parameter x rather setting member variable. (alternatively use unique names parameters , member variables avoid such ambiguities.)
note if had compiled suitable warnings enabled (-wshadow) compiler have been able point out mistakes:
main.cpp: in constructor 'beeboop::beeboop(int)': main.cpp:30:24: warning: declaration of 'x' shadows member of 'beeboop' [-wshadow] beeboop::beeboop (int x) ^ main.cpp:14:13: note: shadowed declaration here int x; ^ main.cpp: in member function 'bool beeboop::setx(int)': main.cpp:36:25: warning: declaration of 'x' shadows member of 'beeboop' [-wshadow] bool beeboop::setx(int x) ^ main.cpp:14:13: note: shadowed declaration here int x;
Comments
Post a Comment