-1
class C {
    public:
    C(int x):
    _x(x){}
    void print(){
        std::cout<<_x<<std::endl;
    }    
    int _x;
};

int main(){
C* c;
c->print(); // print 0 !
return 0;
}

c is a pointer of type C, but it is pointed to nothing ! so why c->print() works ?

for example if I try

int* p;

I can't compile because am trying to point to nothing and compiler stops me.

I should use

int* p = nullptr;

or point to a given reference. should it be the same with a defined type C ? instead of 'int' I use 'C' so why different results?

user438383
  • 5,716
  • 8
  • 28
  • 43
Agnes
  • 111
  • 10
  • 4
    terms like "works" have no meaning in the land of undefined behavior – 463035818_is_not_an_ai Sep 15 '21 at 14:58
  • 3
    Because Undefined Behavior can do *anything*, including producing seemingly-sensible results. – 0x5453 Sep 15 '21 at 14:58
  • 2
    Have a read of [Undefined behavior](https://en.cppreference.com/w/cpp/language/ub) – Richard Critten Sep 15 '21 at 15:00
  • Add to your compiler `-Wall -Werror` or `/W4 /WX` and compiler will report an error: https://godbolt.org/z/6eKdKW54a – Marek R Sep 15 '21 at 15:05
  • 1
    [Look at the results here](http://coliru.stacked-crooked.com/a/c06e7055d002967d). A segmentation fault. – PaulMcKenzie Sep 15 '21 at 15:05
  • 1
    Pretty close to a duplicate here. https://stackoverflow.com/questions/669742/accessing-class-members-on-a-null-pointer – Drew Dormann Sep 15 '21 at 15:07
  • 1
    Crashes on my machine. **Undefined behavior**. Go figure! C++ is not a nanny language, it presumes you know what you are doing, and if you give bad code to the compiler, then there are no guarantees as to the behavior. – Eljay Sep 15 '21 at 15:15

1 Answers1

2

Your program has undefined behaviour. This means that you have done something illegal (indirection through an uninitialized pointer) but the compiler is not required to catch it and the program may appear to work at runtime, but such behaviour is never guaranteed.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312