Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Beginner
Sep 5, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Uses of Reserved Word Operator

In MFC, what does the following declaration do?

CPen::operator HPEN() const;

My understanding of the operator keyword is that you cannot use it to create a new operator; however, this statement seems to declare HPEN() as an operator member of the CPen class.

Not exactly. The word 'operator' in this case doesn't overload a built-in operator but rather, it defines a conversion operator that converts an instance of class CPen into HPEN in a context that needs an HPEN object, for example:

void f(const HPEN & p);

void g()
 CPen pen;
 f(pen); // pen is implicitly converted to HPEN

Note that unlike ordinary overloaded operators, a conversion operator declaration doesn't have a return type (not even void) because the return type is deduced from the type to which the object is converted. In other words, the implied return type in this case is HPEN. The conversion is automatic. You don't call any member function for it to happen.

DevX Pro
Comment and Contribute






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



Thanks for your registration, follow us on our social networks to keep up-to-date