Question

I came across the following code and the method of the class confused me

class X
{
    ......
    operator string () const {return "X"}
    ......
}

Normally the return type is in front of the method. I would appreciate it if someone could explain what this statement does and details regarding this statement

Was it helpful?

Solution

This is not an operator() that returns a string written in a strange way (as you probably thought), it is an implicit conversion operator that can be used to covert the X type to a string type:

X a;
string B = static_cast<string>(a);

Also, take a look at this question.

OTHER TIPS

A conversion operator is a special kind of member function that converts a value of a class type to a value of some other type. It typically looks like this:

operator type() const;

where type represents a type. In your example, it's used to implicitly convert a value of class X to a string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top