0

I'm new to programming and learning classes. I have a class Product and am trying to create an array of products, however my destructor is called three times for two objects and it triggers a breakpoint. Here is some of the code:

`

    class Product {
    private:
        char* name;
        int price;

    public:
        Product();
        Product(const char*, int);
        ~Product();

    };
    `

        Product::Product(const char* name, int price) {
        this->name = new char[strlen(name) + 1];
        strcpy(this->name, name);

        this->price = price;
    }



    Product::~Product() {
    delete[] this->name;
}

    int main() {

    Product redPaint("Red Paint", 25);
    Product bluePaint("Blue Paint", 26);
    Product paint[2] = { redPaint, bluePaint};
}
  • 1
    If this is not a school exercise, use `std::string` instead of `char *`, and all your issues go away. If it is a school exercise, then learn about the [rule of 3](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three). You need to provide a user-defined copy constructor and assignment operator. Probably this question will be closed as a duplicate. – PaulMcKenzie Mar 30 '20 at 18:32
  • The compiler-generated copy constructor will make a shallow copy of your arrays (aka just copying the pointer, not allocating its own array), so you'll have a double-deletion occur when the array deletes the copies of redPaint and bluePaint. – Cory Kramer Mar 30 '20 at 18:34
  • 1
    Does this answer your question? [What is The Rule of Three?](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) – UnholySheep Mar 30 '20 at 18:34
  • @OP Yes, and please read the section titled **Managing Resources** at those links, as that example is almost exactly the same code you have here. – PaulMcKenzie Mar 30 '20 at 18:35
  • thank you very much :D – katipati Mar 30 '20 at 18:44
  • The destructor should be called **four** times; once for `redPaint`, once for `bluePaint`, and once for each of the two objects in `paint`. If you're only seeing three, it's because the program crashed on the third one. – Pete Becker Mar 30 '20 at 19:16

0 Answers0