Why is it possible to use class member functions on an uninitialized object (at least I believe it's uninitialized). The following runs without error:
// A.h
class A {
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) {
A *myClass;
std::cout << myClass->bar(5) << "\n";
}
Now, certainly attempting myClass->foo();
fails, but why can we even use bar()
when all we've declared is that a pointer to A
exists, and is called myClass
? Is this acceptable coding style/is there ever a reason to use this approach?