Conversion Operators

Sometimes, an object must be converted into a built-in type (for instance, a string object passed as an argument to C function such as

 strcmp())

:

 //file Mystring.hclass Mystring {	char *s;	int size;	public:	Mystring(const char *);	Mystring();	//...};#include  	//C str- family of functions#include Mystring.hvoid main() {Mystring str(hello world);int n = strcmp(str, Hello); //compile time error: str is not of 	//type const char *}//end main()

C++ offers an automatic type conversion for such cases. All you have to do is declare a conversion operator in your class definition:

 class Mystring {  //now with conversion operator	char *s;	int size;	public:	Mystring(const char *);	Mystring();	operator const char * () { return s; } //conversion operator	//...};

And all is fine:

 int n = strcmp(str, Hello); //now OK, automatic conversion to			//const char *

Important: conversion operator is different than an ordinary overloaded operator: it should not return a value (not even void) and takes no arguments.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: