Step Twenty-Four  Complex Numbers: Objects and Operator Overloading

Complex Numbers

The complex number system objectives:
Great, now that we have reviewed all of that fun stuff, let's make some complex numbers. We can't just do this:
complex num1;
so we need to do some background work, so let's create a simple complex class:
#include <iostream>
using namespace std;

class Complex {
    Complex(float realpart=0, float imaginarypart=0);
    Complex Add(const Complex &c) const;
    float GetReal() const;
    float GetImaginary() const;
    void SetReal(float r);
    void SetImaginary(float i);
    float real;
    float imaginary;

Complex::Complex(float realpart, float imaginarypart) {

void Complex::SetReal(float r) {
  real = r;

void Complex::SetImaginary(float i) {
  imaginary = i;

float Complex::GetReal() const {
  return real;

float Complex::GetImaginary() const {
  return imaginary;

Complex Complex::Add(const Complex &c) const {
  return Complex(GetReal() + c.GetReal(), GetImaginary() + c.GetImaginary());

Complex operator+(const Complex &c1, const Complex &c2) {
  return c1.Add(c2);

int main(void) {
  Complex x(-1,3);
  Complex y(5,4);
  Complex z = x + y;
  cout << z.GetReal() << '+' << z.GetImaginary() << 'i' << endl;
  return 0;

If you want to see if you understand this, get the program working and then extend it to include subtraction, and multiplication. Before you try division, you might create a new program called fraction.cpp modeled after this one and make all of the changes needed to implement a fraction class (this time with a numerator and denominator instead of a real and imaginary part). The arithmetic operations with fractions are a little more involved because you may have to reduce the resulting fraction. A good approach might be to create a gcd (greatest common divisor) function and use it to reduce your fractions if necessary (i.e. the gcd is not 1). Of course, you want to make sure the denominator never gets set to zero.

Advance to Step Twenty-Five

Return to the Table of Contents