Introduction
C++ में programming करते समय कई बार हमें एक data type को दूसरे data type में बदलने की आवश्यकता होती है। Built-in data types (जैसे int, float) में यह conversion automatically हो जाता है, लेकिन जब हम user-defined types (class objects) के साथ काम करते हैं, तब हमें type conversion को explicitly define करना पड़ता है।
Operator Overloading के context में Type Conversion बहुत महत्वपूर्ण होता है क्योंकि यह objects और basic data types के बीच interaction को संभव बनाता है।
Definition
Type Conversion वह प्रक्रिया है जिसमें एक data type को दूसरे data type में बदला जाता है।
C++ में यह conversion built-in types के साथ automatic होता है, लेकिन class objects के लिए इसे manually define करना पड़ता है।
Type Conversion के प्रकार
1. Basic to Basic (Automatic)
यह conversion compiler automatically करता है।
उदाहरण:
int a = 10;
float b = a; // automatic conversion
2. Basic to Class (Conversion Constructor)
जब basic data type को class object में convert किया जाता है, तो constructor का उपयोग किया जाता है।
Example (Basic → Class)
#include <iostream>
using namespace std;class Demo {
public:
int x; Demo(int v) {
x = v;
} void show() {
cout << "Value: " << x;
}
};int main() {
Demo d1 = 10; // int to class d1.show(); return 0;
}
Output:
Value: 10
3. Class to Basic (Conversion Function)
जब class object को basic data type में convert किया जाता है, तो conversion function का उपयोग किया जाता है।
Syntax
operator dataType() {
// conversion logic
}
Example (Class → Basic)
#include <iostream>
using namespace std;class Demo {
public:
int x; Demo(int v) {
x = v;
} operator int() {
return x;
}
};int main() {
Demo d1(25); int num = d1; // class to int cout << "Value: " << num; return 0;
}
Output:
Value: 25
4. Class to Class Conversion
एक class object को दूसरी class के object में convert किया जा सकता है।
Example
#include <iostream>
using namespace std;class A {
public:
int x; A(int v) {
x = v;
}
};class B {
public:
int y; B(A obj) {
y = obj.x;
} void show() {
cout << "Value: " << y;
}
};int main() {
A a1(50);
B b1 = a1; // class to class b1.show(); return 0;
}
Output:
Value: 50
Important Points
- Constructor → Basic to Class conversion
- Conversion function → Class to Basic conversion
- Conversion explicit या implicit दोनों हो सकता है
- Type compatibility बनाए रखना जरूरी है
निष्कर्ष
Type Conversion C++ में एक महत्वपूर्ण concept है जो different data types के बीच interaction को संभव बनाता है। Operator overloading के साथ इसका उपयोग program को अधिक flexible और powerful बनाता है।