...

View Full Version : Why my operator<< overload doesn't work and prints out a memory location? [C++]



Shaitan00
07-13-2009, 05:36 AM
I'm having an issue using my operator<< overload, I am creating a pointer to a ClassA and storing it in a list, then I get the pointer out of my list using an iterator and when I try to cout << (*iterator) I get the address itself, I don't get the actual operator<< overload to execute ...
This is a reduced version of the code to illustrate what I am doing (the full code is kind of very long)...

I've got a Class A declared as follows:

Header File (A.h)


class A
{
friend ostream& operator<< ( ostream &, const A & );

private:
string sRecord;
};


Implementation (A.cpp)


ostream &operator<<( ostream &sout, const A &a )
{
sout << "Record: " << a.sRecord << endl;
}


Now, this is the calling code from a different class & file:

Implementation (Manager.cpp)


string stringRecord = "Something";
List.push_back(new A(stringRecord));

list<A*>::const_iterator itrA;
itrA = List.begin();

// this is the code that isn't working as expected
// I would exepct this to launch the overloaded operator<< of A but instead it returns (00257200)
cout << (*itrA);


Any clues why this is not working?
Any help would be much appreciated.
Thanks,

ralph l mayo
07-13-2009, 03:03 PM
The type of *itrA is A*, but your ostream op accepts const A&, so you need to do one of two things:

1. dereference again


cout << **itrA;


2. write an ostream operator that accepts A*


ostream& operator<<(ostream& sout, const A* const a)
{
return sout << "Record: " << a->sRecord << endl;
}


(note the return keyword, your other ostream function should have it as well)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum