class B
{
public:
operator B() const{ } // What is this and what is the purpose?
private:
int m_i;
};
So the question is, is that a conversion operator or constructor operator and what is the use of it? Where to use it?
Conversion Operators in C++ C++ supports object oriented design. So we can create classes of some real world objects as concrete types. Sometimes we need to convert some concrete type objects to some other type objects or some primitive datatypes. To make this conversion we can use conversion operator.
1. What is the return type of the conversion operator? Explanation: Conversion operator doesn't have any return type not even void.
The operator overloading defines a type conversion operator that can be used to produce an int type from a Counter object. This operator will be used whenever an implicit or explict conversion of a Counter object to an int is required. Notice that constructors also play a role in type conversion.
It is a conversion function which will never be called implicitly. The Standard actually goes into some depth about this. 12.3.2/1:
A conversion function is never used to convert a (possibly cv-qualified) object to the (possibly cv-qualified) same object type (or a reference to it), to a (possibly cv-qualified) base class of that type (or a reference to it), or to (possibly cv-qualified) void.
And in a footnote,
These conversions are considered as standard conversions for the purposes of overload resolution (13.3.3.1, 13.3.3.1.4) and therefore initialization (8.5) and explicit casts (5.2.9). A conversion to void does not invoke any conversion function (5.2.9). Even though never directly called to perform a conversion, such conversion functions can be declared and can potentially be reached through a call to a virtual conversion function in a base class.
Also, conversion functions are still normal functions and can be called explicitly by name.
The note about virtual functions applies to code like this:
class B;
struct A {
virtual operator B() const = 0;
};
struct B : A
{
public:
operator B() const{ return B(); } // virtual override
private:
int m_i;
};
A const & q = B(); // q has dynamic type B, static type A
B r = q; // Convert A to B using B::operator B()
Pedantic note: "conversion operator" is poor terminology. These are known as conversion functions and they are not considered to be a case of operator overloading, despite the operator
keyword.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With