devxlogo

Uses of Reserved Word Operator

Uses of Reserved Word Operator

Question:
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.

Answer:
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.

See also  Innovation in Crypto Trading Bots
devxblackblue

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