Hello!
I am practising for a test in a few days by trying to write code where I just test stuff.
At the moment I am working with an vector of objects. I have the object Toywhich has the subclass Doll and then the class
AnObject which then uses the class Toy to get its toString() and then print it all withAnObjects:s toString().
The user is to be able to create how many AnObject (dumb name, I know) as he pleases, which all will be added to the vectorobject and when the user is done it is to print out all theAnObjects:s using toString(). This all worked well but I was getting memory leaks, so I tried deleting the brought in *Toyobject in my AnObject class but then the program stops with error after the second while-loop.
Here is the code:
Main:
#include "Toy.h" #include "Doll.h" #include "Puzzle.h" #include <iostream> #include "AnObject.h" #include <vector> using namespace std; int main(){ int size = 0; int val = 99, runda = 0; Toy *tTemp = NULL; vector<AnObject> object; //Toy *temp = NULL; while (val != 0){ cout << "Ange val (1 eller 2): "; cin >> val; cin.ignore(); if (val != 0){ if (val == 1){ tTemp = new Doll(10, "Stefan", 1, "Ful docka", "XXXXL"); AnObject tempO = AnObject(10, tTemp); object.push_back(tempO); //pToy = new AnObject[size]; //pToy[size-1] = AnObject(10, temp); //delete[] temp; size++; } } runda++; } for (int i = 0; i < size; i++){ cout << object[i].toString(); } delete tTemp; /** for (int i = 0; i < size; i++){ cout << pToy[i].toString();//default konstruktorns värden } for (int i = 0; i < size; i++){ pToy[i] = Doll(10, "Stefan", 1, "Ful docka", "XXXL"); cout << pToy[i].toString(); }**/ _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); getchar(); }And then the AnObject.cpp with my destructor where I get the error:
#include "AnObject.h" #include <sstream> using namespace std; AnObject::AnObject(int value, Toy *pos){ this->pos = pos; this->value = value; } string AnObject::toString(){ stringstream sstring; sstring << endl << "Value: " << value << pos->toString(); string result; result = sstring.str(); return result; } AnObject::~AnObject(){ delete pos; }
The other classes work fine and have virtual destructors so they should be fine, if you want me to show them then I will.
Any help would be much appreciated :)