So this is probably going to seem like an obviously simple question. I'm working on a basic project involving linked lists. I have a single link linked-list, within this linked list I have a pointer to an dynamically allocated Object I'd like to be printed, currently I keep getting rubbish data values, I've tested the overloaded insertion stream operator with my objectData class, and it works fine.

this small bit is in a printAll function, within the list class I have, I'm assuming this bit is my main problem

void objectData::printAll(){
  if(head==0){
    
    return;
  }
  Linknode *temp=head;
  while(temp){
    std::cout << temp->objectData  << std::endl; 
    temp=temp->next;
  }
}

so. how should I access what the objectData is pointing to, to print to screen

any help would be much appreciated. Any extra code can be provided if needed, thanks

Your code here is fine. The problem must be occuring somewhere else.

in my main function I'm adding a new object to this list.

objectData *addDataObject = new objectData(value1, value2);
        listTest.insertFront(addDataObject);
        listTest.printAll();

which calls this function firstly,

void objectList::insertFront(objectData *init){
  Linknode *temp= new Linknode();
  temp->objectDataPtr = new objectData(init);
  temp->next=head;
  head=temp;

}

objectDatPtr is a pointer to my objectData on that specific link node.

This is the copy constructor in my objectdata.cpp file

objectData::objectData(objectData *copy){
  value1=copy->getValue1();
  value2=copy->getValue2();
  hitCount=0;
}
void objectList::printAll(){
  if(head==0){
    
    return;
  }
  Linknode *temp=head;
  while(temp){
    std::cout << temp->objectDataPtr  << std::endl; 
    temp=temp->next;
  }
}

and within my objectlist.cpp file I have the overloaded stream insertion operator

std::ostream& operator << (std::ostream& out, objectData &objectDataTemp){
  out << objectDataTemp.getValue1() << ", " << objectDataTemp.getValue2() << ", " << objectDataTemp.getHitCount();

  if(objectDataTemp.getHitCount()==1){
    out << " XXX)";
  }
  else{
    out << " YYY)";
  }

  return out;
}

I keep getting values

like

0x1ea91250
0x1ea911f0
0x1ea91190
0x1ea91130

spewed out instead of my output.'


however if I create my objectData object in the main file, and add the overloaded stream insertion operator code in the main file it prints out like I am expecting

I keep getting values

like

0x1ea91250
0x1ea911f0
0x1ea91190
0x1ea91130

You are printing the pointers' values -- dereferencing (*) will fix this, i.e.

std::cout << * temp->objectData  << std::endl;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.