1

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?

glinka
  • 337
  • 3
  • 13

2 Answers2

1

why can we even use bar() when all we've declared is that a pointer to A exists, and is called myClass?

Because, in general, it's impossible for the compiler to tell whether a pointer will be valid at runtime; so it isn't required to diagnose this error. However, in this case, a decent compiler should be able to issue a warning, as long as you're not building with warnings disabled.

Is this acceptable coding style/is there ever a reason to use this approach?

Absolutely not. Dereferencing an invalid pointer gives undefined behaviour.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
0

Because you can't know if the block of memory where myClass is pointing to is an initialized object, it have right syntax, but undefined behavior, however if want to prevent, you should use -Wall or a similar compiler option (depends on your compiler) and it will warn you about the uninitialized pointer.

dieram3
  • 592
  • 3
  • 7