1

I have a vector of pointers, and I'm trying to overload the ostream operator to make printing easier. However, I can't seem to get the function to be called. Here is my code:

std::vector<Set*> sets;

for (int i = 0; i < sets.size(); i++) {
    std::cout << sets[i] << std::endl;
}

std::ostream& operator<<(std::ostream& out, const Set* s) {
    //Print set code
}

I loop through all the sets and call the specific set for printing by putting sets[i] in the ostream, yet the function is not called. It just prints the address of sets[i]. I had this working when I had a vector of Set, but when I tried to change it to a vector of Set*, I couldn't get it to work. Where am I going wrong?

Lucas
  • 567
  • 1
  • 8
  • 21
  • What is `Set` ? How it is declared ? In shown code `set` is vector of `Set*`, so printing ith element from `set` will obviously print an address. May be you need an element from data structure/container `Set`, use `->` for that. – P0W Nov 23 '13 at 16:54
  • sets is a vector of Set pointers. It contains **pointers**. Pointers are adresses. When you std::cout them, that logically prints adresses. This is what your code asks, this is what you logically get. What else would you want it to do ? – Stephane Rolland Nov 23 '13 at 16:58
  • My intention were for set[i] to be printed out via the overloaded operator<< function. Set is a basically a linked list data structure. I was going to iterate through it and print the elements in the overloaded operator. I tried dereferencing the set with (*sets[i]) also, but that gave me a linking error. I can access the elements and print them using sets[i]->data, if I write my own function, but I can't get it to work if I put that code inside the overloaded << operator because that function is never called. – Lucas Nov 23 '13 at 17:21

1 Answers1

1

Overload resolution is done using the declarations visible to the compiler at the point of call. You'll need to move your operator<< overload, or at least a declaration of it, above the code using it.

And behold, it works: http://ideone.com/1BeACP

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • This worked. I had a function stub in above all the code, but it wasn't working for some reason. When I moved the actual function above the code it worked. Then, when I moved the function back and replaced the function stub, it still worked. Not sure where I went wrong there, but thanks for the help. – Lucas Nov 23 '13 at 19:45