mmostajab
mmostajab

Reputation: 2037

Can conversion functions be non-member functions

Is it possible to define the casting operator from one type to another type outside of the class definition as a non-member function? I know it is possible for other operators like operator- but It is not possible with cast operators. For example for two classes A and B, I tried to define the casting operator outside of the A and B scopes as follows:

operator A(const B& b)
{
    A a(....);
    return a;
}

Upvotes: 10

Views: 3542

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 477040

No, conversion functions must be member functions.

From C++11, [class.conv.fct]/1:

A member function of a class X having no parameters with a name of the form [operator conversion-type-id] specifies a conversion from X to the type specified by the conversion-type-id. Such functions are called conversion functions.

There are no other conversion functions, in particular there are no non-member conversion functions.

Upvotes: 10

ravi
ravi

Reputation: 10733

Conversion operators are specific to class i.e they provide a means to convert your-defined type to some other type. So, they must be the member of a class for which they are serving purpose :-

for e.g:-

class Rational
{
  public:
     operator double ();
};

Here operator double provide a means to convert Rational object to double.

Upvotes: 1

Related Questions