Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 651
mmostajab Avatar asked Nov 18 '14 12:11

mmostajab


People also ask

Can a non-member function be called inside a member function?

Explanation: A non-member function can be called inside a member function but the condition is that the non-member function must be declared before the member function. In the above example, the same approach is followed and it becomes possible to invoke a non-member function thus the answer is the factorial of 5 i.e. 120.

What types of member functions can be declared in C++?

Any function declarations are allowed, with additional syntax elements that are only available for non-static member functions: pure-specifiers, cv-qualifiers, ref-qualifiers, final and override specifiers (since C++11), and member initialization lists . 1) For an object of type X using the class member access operator

What is a non static member function?

Non-static member functions. Within the body of a non-static member function of X, any id-expression E (e.g. an identifier) that resolves to a non-type non-static member of X or of a base class of X, is transformed to a member access expression (*this).E (unless it's already a part of a member access expression).

How are non-static member functions treated during overload resolution?

During overload resolution, non-static member function with a cv-qualifier sequence of class X is treated as follows: no ref-qualifier: the implicit object parameter has type lvalue reference to cv-qualified X and is additionally allowed to bind rvalue implied object argument


Video Answer


2 Answers

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.

like image 68
Kerrek SB Avatar answered Oct 07 '22 12:10

Kerrek SB


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.

like image 27
ravi Avatar answered Oct 07 '22 12:10

ravi