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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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
Thanks for your registration, follow us on our social networks to keep up-to-date