0

Can someone please explain why q[0].data->f3() is not working in function xyz() of class p. while sa.data->f3(); is working however I pushed same object in vector. I am not sure what is causing this issue. While debugging GDB I am getting this error at the same line: Cannot find bound of current function

#include <iostream>
#include <vector>

using namespace std;

class x{
    public:
    virtual int f1() = 0;
    virtual int f3(){
        return 0;
    }
};

class y : public x{
    public:
    virtual int f1(){
        return 0;
    }
    virtual int f3(){
        return 1;
    }
    y(){
    cout<< " in y" << endl;
    }
};


class z{
    public:
    int k;
    x * data;
    z(){
    cout << " in z " << endl;
        y yy;
        data = &yy;
    }
};

class p{
    public:
    vector<z> q;

    int xyz(){
        cout<< "In XYZ " << endl;
        z sa;
        cout << sa.data->f3() << endl;
        q.push_back(sa);
        cout << q[0].data->f3();
    }
};

int main(){

    p pp;
    pp.xyz();
    return 0;
}
  • 1
    `data = &yy` is assigning a pointer to the address of a temporary. `yy` expires after the constructor for `z` finishes. – AndyG Jan 17 '18 at 12:18
  • Thank you @AndyG got the point. – ritesh singh chauhan Jan 17 '18 at 12:25
  • @AndyG one more thing want to ask. why it was working here `cout << sa.data->f3() << endl; ` as it is also out of constructor right? – ritesh singh chauhan Jan 17 '18 at 12:31
  • Sometimes calling a function on an expired pointer to a class still works because the memory hasn't been overwritten yet, and the function doesn't contain any extraordinary logic that might make it trigger a segfault. In the end, accessing expired memory is undefined behavior so anything can happen. It is just as likely that the call would have caused a program crash. – AndyG Jan 17 '18 at 12:33

0 Answers0