1

I have this simple program below:

#include <iostream>            
using namespace std;

class pithikos {

public:
    //constructor
    pithikos(int x, int y){
        xPosition = x;
        yPosition = y;
    }

    //multiplicator of x and y positions
    int xmuly(){
        return xPosition*yPosition;
    }   

private:
    int xPosition;
    int yPosition;
};

int main(void){


//alloccate memory for several number of pithikous
pithikos **pithik = new pithikos*[10];
for (int i = 0; i<10; i++){
     pithik[i] = new pithikos(i,7);
}

cout << pithik[3]->xmuly() << endl; /*simple print statement for one of the pithiks*/

//create pithikos1 
pithikos pithikos1(5,7);
cout << pithikos1.xmuly() << endl;

//delete alloccated memory
for (int i=0; i<10; i++) delete pithik[i];
delete [] pithik;
cout << pithik[4]->xmuly() << endl;
}

The class just takes two numbers and multiplies them and return the value. But I want the oblects to born and die.

So I allocated in this example 10 objects (pithikos) and then I am testing weather it works.

when I ran the program I get this:

21

35

28

my problem is: why do I get the value 28 after I used the command?

delete [] pithik;

how can I delete the objects if not like this?

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185

2 Answers2

0

1-Calling delete will mark the memory area as free. It won't necessary reset its old value.

2-Accessing freed memory will surely cause you an undefined behavior so that's extremely inadvisable thing to try

Spinkoo
  • 2,080
  • 1
  • 7
  • 23
0

Always delete what you create with the new keyword. If you create an array of pointers using new keyword, use delete[] to delete all the pointer elements of the array.

how can I delete the objects if not like this?

This is the correct way of deleting the objects created with new keyword.

why do I get the value 28 after I used the command?

You should not deference a pointer after it is deleted. it results in an undefined behavior. You may get the old value or a nasty segmentation fault.

VHS
  • 9,534
  • 3
  • 19
  • 43