Creating a conversion between two data types

Say I create a class Complex that holds a complex number.

A basic skeleton of it would be:
1
2
3
4
5
6
class Complex
{
public:
     int Real;
     int Imag;
};

Note:this is not the actual code, but just an example...

Now this won't compile:
1
2
3
4
Complex comp;
int integer;
//The Problematic Line:
comp = Complex(integer);


I know that this is because the compiler doesn't know how to convert int to Complex.

So is there a way we can specify the conversion for the compiler?
overload the assignment operator, read this is you don't know about operator overloading http://www.cplusplus.com/doc/tutorial/classes2/
Oh!
Thanks a Lot!!
I knew about Operator overloading by the way.
Thanks again
In this example you need to add a constructor that matches how you are constructing your Complex object - with a single int:
1
2
3
4
5
6
7
8
9
10
11
12
13
14

class Complex
{
public:
	// Construct from a single integer
	Complex(int i) 
	: Real(i)
	, Imag(0)
	{
	}

	int Real;
	int Imag;
};

However when you do that you will also need to add a default constructor for when you construct a Complex object without any parameters:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

class Complex
{
public:
	Complex(): Real(0), Imag(0) {} // Default constructor

	Complex(int i) // Construct from a single integer
	: Real(i)
	, Imag(0)
	{
	}

	int Real;
	int Imag;
};

int main()
{
	Complex comp; // Requites default constructor
	int integer;
	
	comp = Complex(integer); // Requires single int constructor
	return 0;
}


Look under "Constructors and destructors"
http://cplusplus.com/doc/tutorial/classes/
Last edited on
Topic archived. No new replies allowed.