Tag Archives: technical topic

Conversion operator

Hello squids ,

Many of you ,who are studing/studied C++ , may be aware of conversion operator.

In short it may be described as :

A conversion operator can be thought of as a user-defined typecasting operator; it converts its object to a different type in contexts that require that specific type.

And that specific type may be built in as well as user defined .

I like this feature because of the flexibility that it provides to this programming language.

Here I am giving an example which will help you for better understanding of this operator.

class Mystring
char *s;
int size;
Mystring(const char *);
operator const char * () { return s; }

int main()
Mystring str(“hello world”);
int n = strcmp(str, “Hello”);
return 0;

In this example constructor is taking argument const char * and in main “hello world” is passed as an argument in the object.But in next line we are trying to compare a string with an object, which will cause an error , if we don’t use the conversion operator.

So , here conversion operator comes in action and it converts the object into a constant string.

The prototype of conversion function is –

operator type()   {return value;}

here value is the value of class after conversion .type is the data type in which object is to be converted .

Conversion operators differ from ordinary overloaded operators in two ways. First, a conversion operator has no return value (not even void). The return value is inferred from the operator’s name. Secondly, a conversion operator takes no arguments. Conversion operators can convert their objects to any given type, fundamental and user-defined.

Hope this’ll help you guys .

Leave a comment

Filed under Tech-Bowl