Conversion Constructor in C++

Conversion Constructor

Using conversion constructor we can call constructor using ‘=’ i.e. assignment operator. What we mean by this is – 

conversion constructor in C++

Let us look at a few examples –

In the below example we are going to be using a single parameter and use a conversion constructor to assign/re-assign values.

Single Value Conversion Constructor

Let us look at the code below –

#include<iostream>
 
class MyClass {
    int a, b;
 
public:
    MyClass(int i){
        a = i;
        b = i;
    }
    void display()
    {
        std::cout << "a = " << a << ", b = " << b << "\n";
    }
};
 
int main()
{
    MyClass obj1(10);
    obj1.display();
 
    // Single parameter conversion constructor is invoked
    // To re-assign values to obj1 using '=' assigment operator
    obj1 = 20;
    obj1.display();
    
    // fresh object obj2 created using conversion constructor
    MyClass obj2 = 100;
    obj2.display();
    
    return 0;
}

Output

a = 10, b = 10
a = 20, b = 20
a = 100, b = 100

Multiple Parameters Conversion Constructor

Let us look at the example below to understand this case –

#include<iostream>
using namespace std;

class PrepInsta
{
    int x, y;
    public:
    void display(){
        cout << "The values are: " << x << " and " << y << endl;
    }

    // parameterized constructor
    PrepInsta(int a, int b){
        x = a;
        y = b; 
    }
};

int main()
{ 
    PrepInsta p1(50, 50);
    p1.display();

    // Parameterized conversion constructor invoked using multiple variables
    p1 = {100, 200};
    p1.display();
    
    PrepInsta p2 = {200, 200};
    p2.display();

    return 0;
}

Output

The values are: 50 and 50
The values are: 100 and 200
The values are: 200 and 200