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,659
  • 5
  • 25
  • 54

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,481
  • 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