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!
This is undefined behavior, but it will work on most compilers, as foo
is not virtual
and it doesn't use the this
pointer.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With