Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this C++ code work? Uninitialized Pointer [duplicate]

Tags:

c++

Possible Duplicate:
What will happen when I call a member function on a NULL object pointer?

class A {
  public:
    void foo() { cout << "Work";}
    void bar() { this->foo(); }//new edit, works too!
};

class B {
  private:
    A *a; //never initialized
  public:
    A& getA() {
      return *a;
    }
};

void SomeFunction() {
    B *b = new B();
    B& bRef = *b;
    bRef.getA().bar();//edited
    delete b;
}

I called SomeFunction() without initializing "a" and it still prints "Work" correctly. I don't understand why, it should have bailed out with segmentation fault!

like image 999
Aniket Inge Avatar asked Dec 01 '22 21:12

Aniket Inge


2 Answers

This is undefined behavior, but it will work on most compilers, as foo is not virtual and it doesn't use the this pointer.

like image 192
Henrik Avatar answered Mar 24 '23 12:03

Henrik


Remember classes are just a construct of C++. When compiled, all class methods are just static methods that accept a hidden this parameter.

Given that your foo() method never references any data members, it never needs to use it, and so runs fine despite the uninitialised value of this.

like image 43
GazTheDestroyer Avatar answered Mar 24 '23 13:03

GazTheDestroyer