# Complex number program in C++ using class

In this tutorial, we are going to see how we can write a complex number program in c++ using the class object concepts. It is a great example for beginners to understand classes and objects. I hope you have knowledge about these concepts in C++. If you are new to object-oriented concepts, Don’t worry. I’ll explain things in detail. You may understand while we are developing our program. So without any more talking let’s get started with actual coding.

The first thing I am going to do is define our class. Let’s call that file** complex.h**. Since the extension is

**.h**, it is a header file. We are going to make all the files we are going to use in a single project directory. Following is the basic structure of our Class.

```
class Complex
{
private:
float real, img;
};
```

We have named our class Complex. When. we are designing the structure for a class first thing we need to identify is what are the member variables we need to use in the class. We know that a complex number has an imaginary part and a real part. Both those two parts can be floats. So we have created two member variables.

Also notice that we have defined those two member variables under the flag of private. What does that mean? This is the basic idea of Encapsulation. It is a good practice to follow in Object-Oriented Programming. According to that, we have to declare the member variables as private. So those member variables can be only accessible in the class which is we are defining those variables. I am not going to explain the other two modes of declaring variables. You may refer to our * Classes and Objects C++* tutorial to get a better understanding of these basic concepts in OOP.

Now our class has properties. We also need some methods to work with these member variables. methods are just functions which are working with the member variables in the class. To understand which methods to define in our class, we need to identify which functionalities or features should have our class. If we think about this example we are going to define a complex number class. What are the functionalities required by a complex number? The first thing we need is to display the complex number. This will output the contents of the complex number in a proper way. Also, we need to get some inputs and assign those to our member variables because at the moment they hold nothing.

So let’s define our methods. The first one we are going to define is the constructor method. A constructor is a special kind of method that has the same name as the class and its duty is to construct the object. In this example, we use it to assign values to our member variables. we have to define these methods as public because we’re going to call them outside of the class. (It is not necessary for all methods to be declared as public.)

```
class Complex
{
private:
float real, img;
public:
Complex(float real, float img);
};
```

The above code should be in the header file. We are not defining the structure of a method in the same header file. We just write the prototype of the method in the header file and use another CPP file to write the complete definition. So the following code should be located in ** the complex.cpp** file.

```
#include "complex.h"
Complex::Complex(float real, float img)
{
this->real = real;
this->img = img;
}
```

The special operator we have used is called the scope resolution operator. Here we are specifying that we are going to define the method with the name Complex (Right side part of the operator) in the Complex class (Left side part of the operator. )In this case you may be confused a bit. But don’t worry It will be clear in the next steps. The reason to use this operator is we have used the same name for both the member variable and the parameter of the method. You may learn more about this in our * Classes and Objects C++* tutorial. This method will simply assign parameters to the internal member variables. By using this constructor we can make arbitrary complex number objects with the values we supply.

## Printing the Complex number

Our next step is to make a method to print the complex number. So we write the prototype in our header file as above and define the structure of that function in our ** complex.cpp** file. Now our complete header file at the moment is like following.

```
class Complex
{
private:
float real, img;
public:
Complex(float real, float img);
void print(void);
};
```

We are not supplying any arguments to the print function as well as it will not return anything. We just print the output. So We can use the ** iostream** library to print the output. But How we should print it. We know we can access our variables using this pointer. The following code line will do it.

`cout << this->real << " + " << this->img << "i" << endl;`

do the basic job for us. But it will not work well in all cases. For example, if we are printing a number with the real part being 3 and the imaginary part being 5 it will work as expected. But what if we are printing a number with the imaginary part is -5. It will print the number like 3 + -5i. You can see that this is not a proper way to print the complex number. So we can improve our printing part as follows.

`cout << this->real << ((this->img > 0) ? " + " : " - ") << abs(this->img) << "i" << endl;`

I used a ternary operator to format the complex number. You can simply understand it if you read it carefully. Also, the abs() function is used to get the absolute value of the imaginary part.

Also, we can do some more modifications to make our code. Think about a complex number with the imaginary part being zero. Then it is just a real number. So we can print only the real part. Also if the real part is zero, it is a purely imaginary number. In that case, we can only print the imaginary part.

Now our complete code for the ** complex.cpp** file is as follows. Note that we have to include our header fie because we are using it in the code. Also, we included the

**and declared the namespace we are using at the top.**

*iostream*```
#include
#include "complex.h"
using namespace std;
Complex::Complex(float real, float img)
{
this->real = real;
this->img = img;
}
void Complex::print()
{
if (!this->img)
{
cout << this->real << endl;
}
else if (!this->real)
{
cout << this->img << "i" << endl;
}
else
{
cout << this->real << ((this->img > 0) ? " + " : " - ") << abs(this->img) << "i" << endl;
}
}
```

Great, now our printing part is complete. What’s next?

## Getter and Setter methods

As mentioned earlier it is not a good idea to let outer codes directly access the member variables. So we define some methods to access those private properties. So we can use those methods to access and change the private properties of a class.

```
float get_real();
float get_img();
void set_real(float);
void set_img(float);
```

Next, we need to define those definitions in the * complex.cpp* file. Following is the code for that.

```
float Complex::get_real()
{
return this->real;
}
float Complex::get_img()
{
return this->img;
}
void Complex::set_real(float real)
{
this->real = real;
}
void Complex::set_img(float img)
{
this->img = img;
}
```

## Addition and Subtraction of Complex numbers

We can do normal addition, subtraction, and other mathematical operations on primitive data types such as floats, integers, etc. But this is not the same for custom structures such as complex numbers matrices, vectors, etc. For example in complex numbers, we have to add real parts together and imaginary parts together.

For this purpose, there is a concept called operator overloading in c++. We can define custom operators for these specific data structures or classes. The keyword we use for this is the **operator**.

So the result should be * (a+p) + (b+q)i *. We can write the code to accomplish this in C++.

`Complex operator+(Complex);`

The above line is for the header file and we can write the following code in the cpp file.

```
Complex Complex::operator+(Complex number)
{
Complex result(0, 0);
result.set_real(this->get_real() + number.get_real());
result.set_img(this->get_img() + number.get_img());
return result;
}
```

I hope you can understand what is going on in the code. It simply gets the real number from the given complex number and adds it to the current object's real part. the same thing happens for the imaginary part. Then it will return an object of the type of Complex Class.

We can use the same method for subtraction by making a little modification.

```
Complex Complex::operator-(Complex number)
{
Complex result(0, 0);
result.set_real(this->get_real() - number.get_real());
result.set_img(this->get_img() - number.get_img());
return result;
}
```

## Multiplication of Complex numbers

Now we are going to see how we can multiply two complex numbers using classes. First of all, let's see what happens when we are multiplying two complex numbers.

Not in like above case here we have to multiply the real part by both real and imaginary parts of the second number. So the real part of the result is * a*p + b*q * i * i*. As we know i*i is equal to -1. So we can write the real part as

*.*

**ap-bq**The imaginary part is (aq + bp) i. so we can write the following code to do the same thing in the c++ programming language.

```
Complex Complex::operator*(Complex number)
{
Complex result(0, 0);
result.set_real(this->get_real() * number.get_real() - this->get_img() * number.get_img());
result.set_img(this->get_real() * number.get_img() + this->get_img() * number.get_real());
return result;
}
```

## Division of Complex numbers

In the division, we have to do some hard work. It is not possible to just take the answer in a single step. Let's see what happens when we are dividing a complex number by another complex number.

In a problem like this, we can solve it simply if the denominator is a real number. So we can just divide the real part and the imaginary part of the numerator by that real number. What we want to do is try to convert the denominator into a real number. We can do this by multiplying it with its own conjugate. Because in complex numbers we always get a real number by multiplying the complex number by the conjugate. The first thing we want to do is to calculate the conjugate of the denominator. For that, we can use the following two code lines.

```
conjugate.set_real(number.get_real());
conjugate.set_img(number.get_img() * -1);
```

We assumed that the supplied argument is a ‘number’. Now we can multiply the denominator and the numerator of the problem by the taken conjugate. So when we are overloading the operator the numerator is the current object which is pointed by ** this** pointer. The denominator or the complex number which is the divider is the one we are getting as the parameter for the operator. Here we have named it as the number. You have to carefully understand that otherwise you may be confused.

So in the above example, the conjugate is * p - qi*.

Now after we multiply both those up and down parts by the conjugate of the down part we get another complex number. Let's say that is the result of the above step. Its bottom part or the denominator is a real number. That was the purpose of the above step. But its numerator or the above part is still a complex number. Following three code lines are used to obtain those two parts.

```
numerator.set_real(this->get_real() * conjugate.get_real() - this->get_img() * conjugate.get_img());
numerator.set_img(this->get_real() * conjugate.get_img() + this->get_img() * conjugate.get_real());
denominator = (conjugate.get_real() * conjugate.get_real()) + (conjugate.get_img()) * (conjugate.get_img());
```

For the denominator part, we can obtain the number in just a single line because it is a real number.

Now we can obtain the final result by dividing both the real part and the imaginary part of the numerator by the denominator separately. Bellow code is the complete structure of our division operator for complex numbers.

```
Complex Complex::operator/(Complex number)
{
Complex result(0, 0), conjugate(0, 0), numerator(0, 0);
double denominator;
conjugate.set_real(number.get_real());
conjugate.set_img(number.get_img() * -1);
numerator.set_real(this->get_real() * conjugate.get_real() - this->get_img() * conjugate.get_img());
numerator.set_img(this->get_real() * conjugate.get_img() + this->get_img() * conjugate.get_real());
denominator = (conjugate.get_real() * conjugate.get_real()) + (conjugate.get_img()) * (conjugate.get_img());
result.set_real(numerator.get_real() / denominator);
result.set_img(numerator.get_img() / denominator);
return result;
}
```

So that’s all for this tutorial. You can think about what to do to improve this code. For example, we can check the denominator before we divide. Otherwise, it may lead to dividing by zero error. Also, we can use a vector of complex numbers and gett the sum of all of them using the same addition method. I didn’t explain all of them because it will be complicated. Anyway, I’ll attach a complete file with all those modifications and other things we can do with these basic concepts. you can read it and understand. Try to write your own custom codes. Thank you for reading. Hope you learned something.

In this tutorial, we are going to see how we can write a complex number program in c++ using the....

Socket programming is one of the most important features in C. In this document, we are going to....

SQL injection, The classical example of web application vulnerabilities. Actually the term SQL....

#### Thilan Dissanayaka

Hi, I'm Thilan from Srilanka. An undergraduate Engineering student of University of Ruhuna. I love to explorer things about CS, Hacking, Reverse engineering etc.