< Back

Lecture 5- Classes and Objects


As usual, create a directory to hold today's activities:

$ mkdir ~/cs170/labs/lab5 
$ cd ~/cs170/labs/lab5

C++ Classes

The basics of Object Oriented programming carry over between different programming languages. However, the syntax between these languages can vary greatly. You understand the basic concepts you need to understand how to define classes and create objects. Today, I will show you how to define and create classes in C++.


Lab Activity 1

Details

Create a class called ComplexNumber in a file called ComplexNumber.cc and ComplexNumber.h. Your class should be able to represent arbitrary complex numbers. You should be able to add, multiply, and compute the magnitude of these numbers. You should also be able to print complex numbers in it's Euler form, e.g. \(a + bi\), so you can see the result of your work.

Example

  First: 1 + 2i
  Second: 3 + 4i
  First + Second = 4 + 6i
  First * Second = -5 + 10i
  || First || = 2.23607

Note: Your methods for this class should return a new complex number. It should not modify any complex number in place.

Hint

  • Remember that your class definition goes in the .h file. This is specification of the member data, constructors, and method declarations of the class. No implementation takes place here.

  • You need at least 3 methods in your class: add, multiply, and magnitude. Add and Multiply will behave like Fraction's add and multiply: They take a ComplexNumber as a parameter, and return a new ComplexNumber. Magnitude has no parameters, and returns a floating point value.

  • Your implementation for the methods you define should be in your .cc file. Don't forget to specify the namespace for each one of them.

  • Addition of a Complex number is simply adding the two component: real + real is the new real, imaginary + imaginary is the new imaginary.

    Multiplication of a two complex numbers requires some additional algebra. However, it's just using the FOIL method: \[(a + bi) \times (c + di)\]

 

Challenge

For right now, we are going to stick to having a "print" function for our classes. A little bit later in the semester, next week we will cover using some of the advanced techniques in C++ that we saw in Python (operator overloading, etc.) However, it would be useful for this project here as well.

Look up a tutorial on operator overloading in C++. Can you convert your ComplexNumber class to overload the + and * operators?



In-Class Notes