samedi 3 octobre 2020

Copy Constructor containing Base Pointer in Vector

I have been trying to write the copy constructor containing Base* into the vector. But, getting segmentation fault. I copied the contents of vector but pointers are getting copied not the objects. So, inside desctructor it is going to destroy already destroyed object, hence, giving segmentation fault. I know the reason but I am struggling in storing the object inside vector. Thank you in advance for the help. Here is the code which I was trying.

#include <vector>

class Widget {};
class Button : public Widget {};
class Label : public Widget {};

class Window {
    std::vector<Widget*> vec;
public:
    void add(Widget* elem)
    {
        vec.push_back(elem);
    }
    Window() = default;

    //copy constructor
    Window(const Window& obj)
    {
        for (auto ele : obj.vec)
        {
            this->vec.push_back(ele);
        }
    }

    ~Window()
    {
        for (auto ele : vec)
        {
            delete ele;
        }
    }
};

int main()
{
    Window c1;
    c1.add(new Button);
    c1.add(new Label);

    Window c2(c1);
}

Please help me with the mistake I am doing.

Aucun commentaire:

Enregistrer un commentaire