Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a constructor operator or conversion operator?

Tags:

c++

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?

like image 956
deepdive Avatar asked Jun 11 '14 11:06

deepdive


People also ask

What is a conversion operator C++?

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.

What is the return type of the conversion operator?

1. What is the return type of the conversion operator? Explanation: Conversion operator doesn't have any return type not even void.

What is operator overloading explain conversion?

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.


1 Answers

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.

like image 69
Potatoswatter Avatar answered Nov 10 '22 09:11

Potatoswatter