Definition
Conversion Operator is declared like a non-static member function or member function template with no parameters, no explicit return type. They are used to convert between one type and other defined types. It provides a way to implicitly convert an object to its other representation.
Function Call Operator is the ()
operator. It can accept multiple arguments of varying types. When a user-defined class overloads the function call operator, it becomes a FunctionObject type. An object of such a type can be used in a function-call-like expression.
Syntax
Below is the syntax of Conversion Operator.
operator conversionType { // Code Implementation }
conversionType
is a type-id.
Syntax of Function Call Operator is shown below.
ReturnType operator()(DataType1 var1, DataType2 var2, ...) { ReturnType something; // Code return something }
Example
In the below example, operator std::string() const
is called on lines string str = num
. So operator std::string() const
is converting a Complex
object to std::string
.
#include <iostream> #include <string> using namespace std; class Complex { private: int real; int imag; public: Complex(int r, int i) { real = r; imag = i; } // Conversion operator operator std::string() const { string temp = "Real: " + to_string(real) + ", Imag: " + to_string(imag); return temp; } // Function call operator Complex operator() (int rl, int imag) { Complex res(this->real, this->imag); res.real += rl; res.imag += imag; return res; } }; int main() { Complex num = { 1, 2 }; string str = num; /* Calls Conversion operator Output : Real: 1, Imag: 2 */ cout << str << endl; // Calls Function Call Operator str = num(2, 3); // Output : Real: 3, Imag: 5 cout << str << endl; return 0; }
Conversion defined above allows an object to be implicitly converted to an string
. It must return an string
(or whatever type is used, user-defined types like classes or structures can be used as well).
Function Call Operator in the above example returns an Complex
object, and takes two integer as argument.
So function call operator is of the form T operator()
, and conversion operator is of the form operator T()
.