c++objectmemorymember

C++ Successful call to a method of an non-existing object


Why can I call printAlternativ but not print?

class MemTest
{
public:
    MemTest(string);
    ~MemTest();
    void print();
    void printAlternative();
    string name;
};

void MemTest::print() {
    cout << "Print: " << name << "\n";
}

void MemTest::printAlternative() {
    cout << "Print Alternative\n";
}

MemTest::MemTest(string n) {
    cout << "Constructor\n";
    name = n;
}

MemTest::~MemTest() {
    cout << "Destructor\n";
}

void call(MemTest *b) {
    MemTest a("TestName");
    a.print();
    b = &a;
}

int main()
{
    MemTest *b = NULL;
    call(b);
    b->print(); // This crashes
    // b->printAlternative(); This works

    return 0;
}

Solution

  • After call() object get destructed, so now object b does not have any reference of any object and you are trying to access "name" data member of object because of that it get crashed. You can verify it by adding a cout<<"Test line"; after call(b); line in main()

    And why other one is working because member functions are associated with class and get assigned when first time we declare object and compiler only swipe data member in destructor()