C++ Tutorial: Simple program to calculate 2 x 2 matrices with classes

in #programming7 years ago (edited)

Hey!
In this tutorial I will show you how to calculate these matrices.
We will use objects and classes in C++. You can also be a beginner to to this tutorial.

Programs used:
Eclipse as IDE
MingGW GCC as compiler

Let's get started with the 2 x 2 matrix.
This is how our matrix looks like:

What we basically want to calculate is this:

  1. In the main function we create 4 variables of the type double. I will call them a, b, c, and d.

  2. No we will create the first class. I call it Matrix2x2.cpp (a class needs a header file).
    We start with writing the header file (Matrix2x2.h).
    For the calculation we need a result, and also 4 variables. We will declare them in the private area.

  3. Now we need a constructor and a destructor.
    The constructor will be called if we create an object of the class.
    The destructor will be called if we delete an object of the class.
    This will be done in the public area of the class.

  4. In the case of a 2 x 2 matrix, we will write no extra function for the input. Instead we use the parameter constructor with a CBV (call by value).
    Our parameter constructor also gets 4 values. This gets obvious later.
    We also need a function for calculation with no parameters.

  5. Now let's go to the CPP file (Matrix2x2.cpp).
    In there we need to include our header file (Matrix2x2.h).

  6. And we can also create our constructor. In the constructor we have to initalize the variables of our private section from our class.

    'this -> a = 0' means basicly that ' a ' from ' this ' class gets the value ' 0 '

  7. With our parameter constructor we do basicly the same.

    'this -> a = 0' means now, that ' a ' from ' this ' class gets the value of the variable ' a ', wich was sent to the function.
    result doesn't get a variable from the parameter list, so it gets the value 0.

  8. Now we can add the destructor. We can leave it empty.

  9. Now let's get to the function.
    Remember we want to calculate this:

    So what we are goint to do is give our result variable the value of this calculation.
    Because we are in our class we have to write ' this -> a ' and ' this -> b ' and so on.
    After that we return our value.

  10. Almost done.
    Now go into the main function.
    At first we need to include our Matrix2x2.h file

    We have to give our variables a value. We do this with ' cin ' wich requires an input.

  11. After that, we can create our object of the class. Therefore we added the parameter constructor, wich is called basicly like a normal function.

  12. The calculation function has a return value, so we can just write it into an output message.
    We do this by calling the object name with a " . " and then we type in the function name.

  13. And that's it.
    Source code: https://www.dropbox.com/s/bjn7jmelm9vd2cd/Matrix2x2.zip?dl=0

Hope you liked it :)