Create a destructor and call it

I need to create a destructor for my class since i have a lot redundant obj.

I have in my class created destructor like this

1
2
3
4
5
6
7
8
9
10
11
12
13
Class Test
{

public:
vector<pair<int,int>> limeJuice;
~Test()
void merge(test &B)
{
      limeJuice.insert(limeJuice.end(),B.limeJuice.begin(),B.limeJuice.end());

};

};



So when i have to delete a obj can call delete obj. But it does not seem to work.

It says that Test doesn't refer to a value. ...
Last edited on
You've got things backwards when you have this:
1
2
3
4
SomeObject *obj;
obj = new SomeObject;
...
delete obj;

Line 4 calls the destructor, you don't do it the other way around.

In side your destructor you should release any resources that are owned by the object. The most common example is freeing memory.

If your class doesn't have resources that it owns, then you may not need a destructor. The compiler will create a default destructor for you.
I've created a vector of class Test
Vector<Test> Test_object

in which i create a random number of object and place them inside the vector.

I then append there arrays together using some functions, "merging 2 obj"
Which make the 2 second obj redundant, since it is already included in the first one..

thats why i want to free the memory of this object..
Hi! I think you got confused here in 'delete'. This keyword is used for deleting dynamically allocated objects. You dont use that to delete the class itself! The destructor is used to free memories like your
Test_object
for example, objects from inside your class. And btw, the destructor is automatically called everytime the object's scope has finished,(after a function{}), or the class is deleted(if it was used dynamically with 'new').
hmm.. how do i then remove redundant obj.
It take up too much memory..
The vector i've created consist of objects, and since i merge them with the first one, a lot of objects will be redundant, since their information can be found in the first object.
hmm...you could try this pseudocode:
///during merge
for(unsigned int i= 0;i<vector1.size();i++)
{
for(unsigned int j=0;j<vector2.size();j++)
{
if (vector1[i]==vector2[j])
vectormerged.erase(vector[1].size()+j);///depends on how you merged them

}

}

for more info,see http://www.cplusplus.com/reference/vector/vector/erase/

---edited----
now you can use that in your function, hope it helps
Last edited on
My merge function has been added to post#1
Last edited on
So do you mean that after calling merge() you want to delete the items from B? Just clear the vector in B:
1
2
3
4
5
void merge(test &B)
{
      limeJuice.insert(limeJuice.end(),B.limeJuice.begin(),B.limeJuice.end());
      B.limeJuice.clear();
};
Topic archived. No new replies allowed.