anderish
anderish

Reputation: 1759

C++ Struct Default Call Value

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!

Upvotes: 0

Views: 141

Answers (1)

aep
aep

Reputation: 1675

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

Upvotes: 2

Related Questions