0

New to C++ here. Lets say I have a struct defined as:

struct Item {
  string name;
}

In C++, is there a way where I can get the value of name by just calling the object?

Item item;
item.name = "Andy"
cout << item; // --> Output: "Andy"

Thanks!

anderish
  • 1,709
  • 6
  • 25
  • 58
  • 2
    You can overload `<<` to do the job for you. `std::ostream & operator <<(std::ostream & out, const Item & item) { out << item.name; return out; }`. What that means and more wisdom here: [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – user4581301 Feb 12 '20 at 23:32

1 Answers1

2

You need to overload the stream insertion operator operator<< for Item type.

#include <iostream>
#include <string>

struct Item {
  std::string name;
  friend std::ostream& operator<<(std::ostream& stream, const Item& obj);
};
  std::ostream& operator<<(std::ostream& stream, const Item& obj) {
    // Feel free to extend this function to print what you like.
    // You can even do something like 'stream << "Item(" << obj.name << ")";'.
    // The implementation is upto you as long as you return the stream object.
    stream << obj.name;
    return stream;
  }

int main() {
  Item it{"Item1"};
  std::cout << it << std::endl;
}

Try it out yourself

More references on the topic:

reference 1

reference 2

aep
  • 1,583
  • 10
  • 18
  • 1
    Side note: `struct`s generally don't have much use for `friend`s. They default to `public` access, so unless you add restrictions, they are `friend`ly to everyone. – user4581301 Feb 12 '20 at 23:33
  • @user4581301 True, I just wanted to make the solution more general. In the case of public visibility to data members it makes no difference – aep Feb 12 '20 at 23:36
  • No worries. That's why I left it as a note for the self-professed C++ newbie and not a snarkfest. – user4581301 Feb 12 '20 at 23:37