0

how can I make a class return a value without a function?

if I make this class for example:

#include<iostream>
#include<sstream>
using namespace std;

class item{
private:
   string name;
   int quantity;
public:
   string ImAFunction(){
      stringstream ss;
      ss << quantity << ' ' << name;
      string result;
      ss >> result;
      return result;
   }
};

then I'll do this whenever I want to print it

cout<<obj.ImAFunction();

but I want it to be like this

cout<<obj;

I hope I'm clear and not annoying

ZKlack
  • 1
  • 2
    You are supposed to overload `operator< – walnut Feb 20 '20 at 16:53
  • on first sight your question looks like you want a conversion, but you dont need that. The dupe tells you the "right" way. Fwiw you could write a conversion operator as member : `explicit operator std::string() { return ImAFunction(); }` but that only lets you turn an `item` into a `std::string`, it wouldnt allow you to write `cout << obj;` – 463035818_is_not_a_number Feb 20 '20 at 16:56
  • @idclev463035818 will that make the objects automatically convert to string whenever needed like in 'code' string str = obj; 'code' also do I write the conversion function inside the class or on the global of item.cpp or in the global of main.cpp? thanks for helping. – ZKlack Feb 20 '20 at 17:09
  • see here: https://stackoverflow.com/questions/1307876/how-do-conversion-operators-work-in-c – 463035818_is_not_a_number Feb 20 '20 at 17:13
  • @idclev463035818 thanks again. – ZKlack Feb 20 '20 at 17:36

0 Answers0