0

Could someone tell me why does this code work while mA is null? See the output below. mA is null but invoking the write method works.

class A {

public:
    void write();

};

void A::write() {
    std::cout << "A::write()" << std::endl;
}

class B {

private:
    A *mA;

public:
    void writea();

};

void B::writea() {
    std::cout << mA << std::endl;
    std::cout << &(*mA) << std::endl;

    (*mA).write();
}


int main()
{ 
    B *b = new B();
    b->writea();
    delete b;
}

Output:

00000000
00000000
A::write()

Thanks in advance.

Tibeben
  • 181
  • 1
  • 5
  • You have called _undefined behavior_, and your question is even a duplicate. – πάντα ῥεῖ Sep 23 '18 at 20:11
  • Put yourself into a compiler's place. It knows the address of the function at the compile time, it does not depend on `this`. But if you try to do anything with the object inside this function, you'll get a segmentation fault, because you need valid `this` to access the object. – Evg Sep 23 '18 at 20:17

0 Answers0