How would I make a class in C++ that when referenced, returns a member?

I have a class, and would like the class to return a member when referenced.

Desired syntax because my question was unclear:

SomeClass some_var = "Something I want to be returned from SomeClass when referenced";
cout << some_var; // How would this return the string I provided?

I know this is a very simple example, and this could be replaced with a std::string, but how would I do this?

1 Like

Basically, you need to add something that will handle this you need to “overload” or create a custom case for your class to handle outputs (<< operator). Here you go:

class A {
public:
  int i;
};

std::ostream& operator<<(std::ostream &strm, const A &a) {
  return strm << "A(" << a.i << ")";
}

Source 1 Source 2

2 Likes

Additionally, you could define a cast operator/user-defined conversion function that creates a string from your class:

class A {
  std::string text
  operator std::string() const {
    return "A(" + text + ")"
  }
}

Edit: I added the class block around the cast operator/user-defined conversion function.

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.