Conversion Constructor in C++



In C++, a conversion constructor is a special type of constructor that takes only one argument. It enables automatic type conversion from the argument's type to the class type.

When an object of the class to be created from a single value(int). then the compiler will call the conversion constructor to create the object from that value. This can be implicit conversion of a value into a class object.

Creating Conversion Constructor

Following is the syntax to the Conversion Constructor in C++:

class ClassName {
public:
    ClassName(Type arg);  // Conversion constructor
};

Here, Type arg accepts a single value of some type (e.g: int, float, string, etc.) that is used to construct the object. It accepts only one parameter (or additional ones with default values) and like all constructors, the Conversion Constructor also does not have any return value, not even void. but, it initializes and constructs the object of the class.

Temperature Conversion Example using Conversion Constructor

This program converts a Fahrenheit value (98.6) to Celsius using a conversion constructor:

#include<iostream>
using namespace std;
class Temperature {
   float celsius;
public:
   // Conversion constructor
   Temperature(float f) {
      celsius = (f - 32) * 5 / 9;
   }
   void display() {
      cout<<"Temperature in Celsius: "<<celsius<<endl;
   }
};
int main() {
   // Implicit conversion from float to Temperature object
   Temperature t = 98.6;
   t.display();
   return 0;
}

Following is the output to the above program:

Temperature in Celsius: 37

Distance Conversion Example using Conversion Constructor

In this example, we use a conversion constructor to convert kilometers(5) into meters(5000):

#include<iostream>
using namespace std;
class Distance {
   int meters;
public:
   // Conversion constructor
   Distance(int km) {
      meters = km * 1000;
   }
   void display() {
      cout<<"Distance in meters: "<< meters<<endl;
   }
};
int main() {
   // Implicit conversion from int (kilometers) to Distance object
   Distance d = 5;
   d.display();
   return 0;
}

Following is the output to the above program:

Distance in meters: 5000
Revathi Satya Kondra
Revathi Satya Kondra

Technical Content Writer, Tutorialspoint

Updated on: 2025-05-30T17:36:12+05:30

829 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements