c++ - Using class member functions without initialization -
this question has answer here:
- accessing class members on null pointer 8 answers
why possible use class member functions on uninitialized object (at least believe it's uninitialized). following runs without error:
// a.h class { public: explicit a(int n) : n_(n) {}; ~a() {}; int foo() { return n_; }; int bar(int i) { return i; }; private: int n_; };
with
// main.cc #include <iostream> #include "a.h" int main(int argc, char **argv) { *myclass; std::cout << myclass->bar(5) << "\n"; }
now, attempting myclass->foo();
fails, why can use bar()
when we've declared pointer a
exists, , called myclass
? acceptable coding style/is there ever reason use approach?
why can use
bar()
when we've declared pointera
exists, , calledmyclass
?
because, in general, it's impossible compiler tell whether pointer valid @ runtime; isn't required diagnose error. however, in case, decent compiler should able issue warning, long you're not building warnings disabled.
is acceptable coding style/is there ever reason use approach?
absolutely not. dereferencing invalid pointer gives undefined behaviour.
Comments
Post a Comment