xxdraxulis
xxdraxulis

Reputation: 55

C++ return object member variable when object is called?

How do you make a class for example return a member variable when it is called? Say:

class Person {
    std::string name;

    // Constructor and Destructor go here..
};

Person mike = "Mike";

// /!\ How do you make "mike" return "Mike" directly when the object mike is called?
//  This is the same thing like an int return its value and a vector returns its members (scalars)
std::string name = mike;

Additional Edit: The cast operator is not a good option here as it ruins the way a type is written. For example std::string name = static_cast<string>(mike); is a horrible way to achieve my target.

Upvotes: 2

Views: 642

Answers (1)

cigien
cigien

Reputation: 60208

You're looking for a conversion operator, which is written like this:

class Person {
    std::string name;
 public:
    Person(char const * name) : name(name) {}
    operator std::string () const { return name; }
};

Here's a demo.

You could also make the conversion operator a template, like this:

template<typename T>
operator T() const { return name; }

Here's a demo.

Upvotes: 3

Related Questions