Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Jan 2005
    Posts
    74
    Thanks
    0
    Thanked 1 Time in 1 Post

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

    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)
    Code:
    class A
    {
    	friend ostream& operator<< ( ostream &, const A & );
    
    private:
    	string sRecord;
    };
    Implementation (A.cpp)
    Code:
    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)
    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);
    Any clues why this is not working?
    Any help would be much appreciated.
    Thanks,

  • #2
    Regular Coder ralph l mayo's Avatar
    Join Date
    Nov 2005
    Posts
    951
    Thanks
    1
    Thanked 31 Times in 29 Posts
    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
    Code:
    cout << **itrA;
    2. write an ostream operator that accepts A*
    Code:
    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)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •