I'd like to make one directional list of objects in C++. I've got 3 classes: BasicMiachine,Desktop,Laptop. Two last classses extends BasicMachine. What I want to do is make a list of object (Desktop,Laptop) using only one list. In Basic Class which is abstract class (because I have declare one method as virtual) I have a field which is a pointer to next object is a BasicClass type. Below is my code:
int main () {
BasicClass* headList= NULL;
BasicClass* iterator = NULL;
while(....)
{
switch(.....){
case 1:
addNewComputer(headList,iterator,numberOfObjects);
break;
}
}
void static addNewComputer(BasicClass* headList, BasicClass* iterator,short numberOfObjects)
{
short choice;
cout<<"What is your machine?"<<endl<<"1) Desktop or2) Laptop"<<endl;
cout<<"Your choice: "; cin>>choice;
if(choice== 1)
{
//Add some data to variables// ....//
if(numberOfObjects == 0)
{
headList = new Desktop(wysokosc,dlugosc,szerokosc, taktowanieProcesora, numerIdentyfikacyjny, typProcesora, nazwaWSieci,ID);
iterator= headList ;
iterator->nextObject = NULL;
}
else
{
BasicClass* tmpIterator= NULL;
tmpIterator= headList ;
tmpIterator->nextObject = new Desktop(wysokosc,dlugosc,szerokosc, taktowanieProcesora, numerIdentyfikacyjny, typProcesora, nazwaWSieci,ID);
tmpIterator= pomocniczyWskaznik -> nextObject;
tmpIterator->nextObject = NULL;
}
}
else if(choice == 2)
{
//It is the same as above but I add here a La
}
};
After I add one and second computer I got an error like: "Access violation writing location 0x00000050." Is it a problem with pointers? I use BasicClass type pointers to hold both objects (Desktop, Laptop).
You make the classic mistake of passing pointers by value instead of by reference.
Change addNewComputer
to e.g.
void static addNewComputer(BasicClass*& headList, BasicClass*& iterator,short numberOfObjects)
and things should work better.
I suggest you to take a look to standard containers. Anyway, the problem is that your are passing pointers by value, so when you call "new" the pointer inside addNewComputer() points to a new memory direction and when the function returns, headList and iterator are null (notice the memory leak issue). To solve your problem, you need to pass headList and iterator by reference i.e.
void static addNewComputer(BasicClass*& headList, BasicClass*& iterator,short numberOfObjects)
Hope this help.
User contributions licensed under CC BY-SA 3.0