Conversion Constructor in C++

Conversion Constructor

On this page we will discuss about conversion constructor in C++. Constructors are special functions in C++, these are used widely to initialize the objects with values for a class. Conversion constructor is a single parameter constructor.It is declared without the function specifier explicit.
conversion constructor in C++

Conversion Constructor in C++ Language

The compiler uses conversion constructor to convert objects from the type of the single parameter to the type of the conversion constructor’s class.

Usage of conversion constructor  

  1. In return value of a function
  2. As a parameter to a function

New way of calling Constructor

Usual way of calling a constructor is ClassName(variables).
For example:  PrepInsta(int x) or PrepInsta(int x, int y)

Using conversion constructor we can call constructor by using assignment operator (=).

For Example –
1. ClassName obj = val (PrepInsta obj = 10)
2. ClassName obj = {val1, val2 ..} (PrepInsta obj = {10, 20})

Single Value Conversion Constructor

Let us look at the code below –

Run

#include <iostream>
using namespace std;

// base class
class Animal {

   public:
    void jump() {
        cout << "I can jump!" << endl;
    }

    void sit() {
        cout << "I can sit!" << endl;
    }
};

// derived class
class Dog : public Animal {
 
   public:
    void bark() {
        cout << "I can bark! Woof woof!!" << endl;
    }
};

int main() {
    // Create object of the Dog class
    Dog doggy;

    // Calling members of the base class
    doggy.jump();
    doggy.sit();

    // Calling member of the derived class
    doggy.bark();

    return 0;
}

Output

I can jump!
I can sit! 
I can bark! Woof woof!! 

Multiple Parameters Conversion Constructor

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

Run
#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

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription