1

If I have a class Rectangle

class Rectangle{

 private:
   double width;
   double height;


   public:
      void    Set(double w , double l){
          width   = w;
          height  = l;
      }
};

and I decleare an object such:

Rectangle *Obj;

and then use Set function as

Obj->Set(6.0, 9.0);

The program runs and displays no error, whereas according to me it should displayvan error, as i have not initialised the pointer.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
  • 2
    C++ does not track at runtime whether a pointer is initialized or not. The compiler may give you a warning about usage of uninitialized variable if you set high enough warning level. – Serge Rogatch Oct 06 '15 at 07:08
  • 1
    Fraid not. Exactly what to do with an uninitialized pointer is left up to the implementation. Typically the pointer will just contain whatever crap happened to be on the stack and if it doesn't point anywhere fatal, you're good to go. Except you're not. Something just got smashed and you won't find out until later. – user4581301 Oct 06 '15 at 07:09

3 Answers3

4

Using an uninitialized pointer is undefined behaviour. This means that the implementation can do whatever it wants, or do nothing at all.

The behaviour just isn't defined.

Tony The Lion
  • 61,704
  • 67
  • 242
  • 415
1

I just compiled this in Visual studio , I got below error.May be the compiler that you choose does not have these checks? What is the compiler that you are using ?

error C4700: uninitialized local variable 'Obj' used
g4ur4v
  • 3,210
  • 5
  • 32
  • 57
  • g++ version should be something along the lines of `warning: 'Obj' is used uninitialized in this function [-Wuninitialized]` – user4581301 Oct 06 '15 at 07:13
1

Accessing the value of an uninitialised pointer - let alone dereferencing it - gives undefined behaviour.

The nature of undefined behaviour is that any result is permitted, but there is no requirement for anything in particular. That word "any" is pretty wide ranging .... Emitting an error message is correct. Not emitting an error message is correct. Reformatting your hard drive and installing a different operating system is correct (although unlikely in practice).

Peter
  • 35,646
  • 4
  • 32
  • 74