Let’s go through Conversion Constructor and Conversion Operator in C++, with clear theory and examples:
A conversion constructor is a constructor that can be called with a single argument.
It converts one type into another by constructing an object of a class.
class ClassName {
public:
ClassName(Type arg); // Single-argument constructor
};
#include<iostream>
using namespace std;
class Complex {
double real, imag;
public:
// Conversion constructor: int → Complex
Complex(int r) {
real = r;
imag = 0;
}
void display() {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c = 5; // Implicit call: int → Complex
c.display(); // Output: 5 + 0i
}