Jump to content
Xtreme .Net Talk

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


Recommended Posts

Posted

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;
};
[/Code]

 

Implementation (A.cpp)

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

 

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

 

Implementation (Manager.cpp)

[Code]
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);
[/Code]

 

Any clues why this is not working?

Any help would be much appreciated.

Thanks,

  • Leaders
Posted (edited)

[PLAIN]Re: Why my operator<< overload doesn't work and prints out a memory location? [C++][/PLAIN]

 

I'm a little fuzzy on my C++ but I think this is your issue.

 

Your overload defines an operator << for ostream and &A (reference to A), but in usage, you have an ostream and list<A*>::const_iterator. The two are not the same, and your operator won't be used.

 

[edit]Or not.[/edit]

I guess the Begin method returns a sort pointer? If this is the case, and you have a list of pointers, then you are still passing an A* instead of an A&, though how you get from A* to A&, I'm not sure. Maybe one of these:

 

&**itrA

**itrA (compiler will convert to a reference?)

Edited by snarfblam
[sIGPIC]e[/sIGPIC]

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...