MarcusV
MarcusV

Reputation: 353

Fill a list with pointers - c++

I'm trying to fill a list with pointers in one class and use it in another class but i always take the same result. I know that i must create a new object every time but it doesn't seem to work. Any help is appreciated, thank you in advance. Here is the code:

list<Class1*> FillList() {  //Class1 is a superclass

for (int i = 0; i < 2; ++i) {
  //mvar is a Class1 object pointer
    mvar = new Class1;
    mvar = next();  //returns &Class2 (subclass) object witch has "ID" (int) and
                    //"Terms" (string) as parameters

    if (mvar->ID() != -1) { 
      mlist.push_back(mvar);
      mvar = NULL; 
    }    
}
return mlist;
mlist.clear(); 
}


//Use of FillList in the other class

 list<Class1*> mlist2 = object->FillList();  //returns mlist

 while (mlist2.front()->id() != -1) {

        index(mlist2.front());  //do something with it - Expects Class1 pointer
        ...
        mlist2 = object->FillList();
}

*I tried to use:

mlist.push_back(new Class1(mvar->ID()); 

instead of:

mlist.push_back(mvar);.

and it works but when the program gets to index() the function expects a Class1 object pointer instead of an int (which is the type of the ID() )

Upvotes: 0

Views: 316

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283614

This code

mvar = new Class1;
mvar = next();

overwrites the only pointer you had to the brand-new Class1 object, leaking it. You have to create only the object you want to keep. You can't create objects in steps, and there is no garbage collection to fix mistakes like this.

Upvotes: 1

Related Questions