Rajeshwar
Rajeshwar

Reputation: 11651

How to know when the conversion operator is called

I have been reading about the conversion operator however I am still not sure when the conversion operator is called. Consider the following example:

class foo
{
public:
    operator char*()
    {
        return "SomeText";
    }
};


foo d;
const char* m = static_cast<char*>(d);

Why is the conversion operator called with this cast ? Which operator is calling it ?

Upvotes: 1

Views: 77

Answers (1)

Marco A.
Marco A.

Reputation: 43662

Citing from static_cast documentation

If a temporary object of type new_type can be declared and initialized with expression, as by new_type Temp(expression);, which may involve implicit conversions, a call to the constructor of new_type or a call to a user-defined conversion operator, then static_cast<new_type>(expression) computes and returns the value of that temporary object.

And that's not an operator as T.C. noted, it's a conversion function

Upvotes: 1

Related Questions