Home > database >  C vector not saving the parent of an object
C vector not saving the parent of an object

Time:11-17

Suppose I Have class A like this

class A {
    public:int num;
    public:A* parent;

    A(){};

    A::A (const A &s)
    {
        this->num = s.num;
    }
};

Inside the main function I make two object from class A

int main()
{
    A a1;
    a1.num = 2;
    
    A a2 = a1;
    a2.parent = &a1;
    
    cout << a2.parent->num << endl;

    return 0;
}

it will obviously print 2 but when I make a vector of class A and push a2 object into the vector like this

int main()
{
    A a1;
    a1.num =2;
    
    A a2 = a1;
    a2.parent = &a1;
    
    vector <A> List;
    List.push_back(a2);
    

    A temp = List.front();
    
    cout << temp.parent->num << endl;

    return 0;
}

cmd is crashing and its not printing anything . Could anyone help me .

PS: I didn't know what is the correct way to assign the second object into the parent of the first object inside the deep copy constructor that's why I assigned it manually .

CodePudding user response:

Your problem is here:

A::A (const A &s)
{
        this->num = s.num;
}

This is a copy constructor. It is triggered on A temp = List.front();

However, it doesn't set this->parent, which remains uninitialized. So, next line, when you do temp.parent->num you access uninitialized memory.

You should also do: (Or remove it altogether as Some Programmer dude suggests)

A::A (const A &s)
{
        this->num = s.num;
        this->parent = s.parent;
}

But take some time to look up on the rule of three. And know that vectors will reallocate and may invalidate the address of some objects. This will come to bite you if you set an object from a vector as a parent of another one.

  • Related