0
case 4: //  ----------------------------------------    Delete Customer
                cout << "Enter your Customer ID:" << endl;
                cin >> exist_id;
                for (int i = 0; i <= cnum; i++) {
                    if (c[i].C_ID() == exist_id) {
                        cc = 't'; // check to set customer found.

                        c[i].~customer(); // error occurs here

                        c[i].id(NULL);
                        cout << "Deletion Successful" << endl << endl;
                        break;
                    }
                };

                if (cont(cc) == false) {
                    cout << "CUSTOMER NOT FOUND" << endl << endl;
                }
                cc = 'f';
                //system("CLS");
                break;

I the above case i am having the Exception thrown: read access violation. _Pnext was 0x148F854. Error.

The code ran perfectly on 2-3-2020. But today this error arises while deleting the customer from an array.

Visual Studio Error alert

1 Answers1

0

Destructors in C++ are called by default when the object dies/destroys to handle the not needed allocated memory for the first place and it shouldn't be called anywhere else.

In your case, I think that the best practice to do is to create a member function delete_customer in customer class that has the exact code in the destructor.

Or, to not repeat the code twice, you can call delete_customer function in the destructor to be called when the object dies.

Hope this will fix your issue!

Kasper
  • 588
  • 3
  • 16
  • your fix might work yes. But the code worked by just copying it into another C++ empty project. This fix confused me more lol. – Saeed Rehman May 11 '20 at 20:20
  • @SaeedRehman Just because it appears to work sometimes doesn't mean it's correct. You should not be explicitly calling the destructor unless you're in one of the situations mentioned [here](https://stackoverflow.com/q/14187006/9254539). You probably have a load of undefined behavior that happens to appear to work. – eesiraed May 11 '20 at 21:15
  • I absolutely agree with @BessieTheCow – Kasper May 11 '20 at 23:06
  • Alright I'll look into this topic in detail. Thanks @BessieTheCow. – Saeed Rehman May 12 '20 at 01:39