Im a bit confused on what exactly a conversion constructor is, how its called, and whats its use is.
I was given this following code by my professor as an example of conversion constructor (the comments included are hers, not mine).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
#include <iostream>
using namespace std;
class IntClass
{
private:
int value;
public:
// Convert constructor from int.
IntClass(int intValue)
{
value = intValue;
}
int getValue(){ return value; }
};
// Function prototypes.
void printValue(IntClass);
IntClass f(int);
int main()
{
// Initialize with an int.
IntClass intObject = 23;
cout << "The value is " << intObject.getValue() << endl;
// Assign an int.
intObject = 24;
cout << "The value is " << intObject.getValue() << endl;
// Pass an int to a function expecting IntClass.
cout << "The value is ";
printValue(25);
cout << endl;
// Demonstrate conversion on a return.
intObject = f(26);
cout << "The value is ";
printValue(intObject);
return 0;
}
//*******************************************
// This function returns an int even though *
// an IntClass object is declared as the *
// return type. *
//*******************************************
IntClass f(int intValue)
{
return intValue;
}
//*******************************************
// Prints the int value inside an IntClass *
// object. *
//*******************************************
void printValue(IntClass x)
{
cout << x.getValue();
}
|
Okay, so what I understand from this code is the following:
(1)First, the number 23 is assigned to a newly created intClass IntObject. Because of this assignment statement, the 'conversion constructor' is called and so the number 23 (which is originally an int), is now converted to of type intClass.
(2)Now the number 24 is assigned to intObject. 24 is of type intClass.
(3)Next, 25 is passed to the printValue function, which implicitly converts it to type intClass, as the parameter is expecting an object of type intClass.
(4) Lastly, an int is passed to the function called 'f', and an int is returned (even though the return type is intClass). The return is then assigned to an intClass object. Thus, 26 is of type intClass.
If I got all this right let me know.
Now, what exactly are the advantages of a conversion constructor? I've never used one in any of my programs and dont know how it could ever come in handy.