Assignment: Type Conversion in C++
Objective:
To implement type conversion in C++ using:
1. Basic to Class conversion
2. Class to Basic conversion
Program 1: Basic to Class Type Conversion
Key Concept:
This program demonstrates how a basic data type (like int) can be converted to a
class type using a constructor.
Code:
#include <iostream>
using namespace std;
class Number {
private:
int value;
public:
Number(int x) {
value = x;
}
void display() {
cout << "Value: " << value << endl;
}
};
int main() {
int x = 42;
Number n = x;
n.display();
return 0;
}
Outcome:
The program successfully converts an integer (int x = 42) into a class object
(Number n). This is done using a constructor that accepts an integer.
Program 2: Class to Basic Type Conversion
Key Concept:
This program demonstrates how to convert a class object to a basic data type using
a type conversion operator function.
Code:
#include <iostream>
using namespace std;
class Number {
private:
int value;
public:
Number(int x) {
value = x;
}
operator int() {
return value;
}
void display() {
cout << "Value: " << value << endl;
}
};
int main() {
Number n(75);
int x = n;
cout << "Converted int: " << x << endl;
return 0;
}
Outcome:
The program demonstrates successful conversion of a class object into a basic type
(int) using the operator int() function.
Conclusion:
- We implemented Basic to Class conversion using a constructor.
- We implemented Class to Basic conversion using a conversion operator.
- These conversions help in integrating user-defined types with built-in types
seamlessly.