Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
Feb 20, 1998

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

class Mystring {
	char *s;
	int size;
	public:
	Mystring(const char *);
	Mystring();
	//...
};

#include  	//C str- family of functions
#include Mystring.h

void 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.
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap