Conversion Operators

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



 //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.

See also  Redefining Energy Management: Advanced Solutions for Modern Buildings

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist