• Windows Programming
  • UNIX/Linux Programming
  • General C++ Programming
  • Matrix assignment operator

  Matrix assignment operator

matrix assignment operator c

Matrix Classes in C++ - The Source File

This is the second part in a two part article series on how to create a robust, extensible and reusable matrix class for the necessary numerical linear algebra work needed for algorithms in quantitative finance. In order to familiarise yourself with the specification and declaration of the class, please read the first article on the matrix header file before continuing.

Our task with the source file is to implement all of the methods outlined in the header file. In particular we need to implement methods for the following:

  • Constructors (parameter and copy), destructor and assignment operator
  • Matrix mathematical methods: Addition, subtraction, multiplication and the transpose
  • Matrix/scalar element-wise mathematical methods: Addition, substraction, multiplication and division
  • Matrix/vector multiplication methods
  • Element-wise access (const and non-const)

We will begin with the construction, assignment and destruction of the class.

Allocation and Deallocation

The first method to implement is the constructor, with paramaters. The constructor takes three arguments - the number of rows, the number of columns and an initial type value to populate the matrix with. Since the "vector of vectors" constructor has already been called at this stage, we need to call its resize method in order to have enough elements to act as the row containers. Once the matrix mat has been resized, we need to resize each individual vector within the rows to the length representing the number of columns. The resize method can take an optional argument, which will initialise all elements to that particular value. Finally we adjust the private rows and cols unsigned integers to store the new row and column counts:

The copy constructor has a straightforward implementation. Since we have not used any dynamic memory allocation , we simply need to copy each private member from the corresponding copy matrix rhs :

The destructor is even simpler. Since there is no dynamic memory allocation, we don't need to do anything. We can let the compiler handle the destruction of the individual type members ( mat , rows and cols ):

The assignment operator is somewhat more complicated than the other construction/destruction methods. The first two lines of the method implementation check that the addresses of the two matrices aren't identical (i.e. we're not trying to assign a matrix to itself). If this is the case, then just return the dereferenced pointer to the current object ( *this ). This is purely for performance reasons. Why go through the process of copying exactly the same data into itself if it is already identical?

However, if the matrix addresses differ, then we resize the old matrix to the be the same size as the rhs matrix. Once that is complete we then populate the values element-wise and finally adjust the members holding the number of rows and columns. We then return the dereferenced pointer to this . This is a common pattern for assignment operators and is considered good practice:

Mathematical Operators Implementation

The next part of the implementation concerns the methods overloading the binary operators that allow matrix algebra such as addition, subtraction and multiplication. There are two types of operators to be overloaded here. The first is operation without assignment . The second is operation with assignment . The first type of operator method creates a new matrix to store the result of an operation (such as addition), while the second type applies the result of the operation into the left-hand argument. For instance the first type will produce a new matrix $C$, from the equation $C=A+B$. The second type will overwrite $A$ with the result of $A+B$.

The first operator to implementation is that for addition without assignment. A new matrix result is created with initial value $0$. Then each element is iterated through to be the pairwise sum of the this matrix and the new right hand side matrix rhs . Notice that we use the pointer dereferencing syntax with this when accessing the element values: this->mat[i][j] . This is identical to writing (*this).mat[i][j] . We must dereference the pointer before we can access the underlying object. Finally, we return the result:

Note that this can be a particularly expensive operation. We are creating a new matrix for every call of this method. However, modern compilers are smart enough to make sure that this operation is not as performance heavy as it used to be, so for our current needs we are justified in creating the matrix here. Note again that if we were to return a matrix by reference and then create the matrix within the class via the new operator, we would have an error as the matrix object would go out of scope as soon as the method returned.

The operation with assignment method for addition is carried out slightly differently. It DOES return a reference to an object, but this is fine since the object reference it returns is to this , which exists outside of the scope of the method. The method itself makes use of the operator+= that is bound to the type object. Thus when we carry out the line this->mat[i][j] += rhs(i,j); we are making use of the types own operator overload. Finally, we return a dereferenced pointer to this giving us back the modified matrix:

The two matrix subtraction operators operator- and operator-= are almost identical to the addition variants, so I won't explain them here. If you wish to see their implementation, have a look at the full listing below.

I will discuss the matrix multiplication methods though as their syntax is sufficiently different to warrant explanation. The first operator is that without assignment, operator* . We can use this to carry out an equation of the form $C = A \times B$. The first part of the method creates a new result matrix that has the same size as the right hand side matrix, rhs . Then we perform the triple loop associated with matrix multiplication. We iterate over each element in the result matrix and assign it the value of this->mat[i][k] * rhs(k,j) , i.e. the value of $A_{ik} \times B_{kj}$, for $k \in \{0,…,M-1\}$:

The implementation of the operator*= is far simpler, but only because we are building on what already exists. The first line creates a new matrix called result which stores the result of multiplying the dereferenced pointer to this and the right hand side matrix, rhs . The second line then sets this to be equal to the result above. This is necessary as if it was carried out in one step, data would be overwritten before it could be used, creating an incorrect result. Finally the referenced pointer to this is returned. Most of the work is carried out by the operator* which is defined above. The listing is as follows:

We also wish to apply scalar element-wise operations to the matrix, in particular element-wise scalar addition, subtraction, multiplication and division. Since they are all very similar, I will only provide explanation for the addition operator. The first point of note is that the parameter is now a const T&M , i.e. a reference to a const type. This is the scalar value that will be added to all matrix elements. We then create a new result matrix as before, of identical size to this . Then we iterate over the elements of the result matrix and set their values equal to the sum of the individual elements of this and our type value, rhs . Finally, we return the result matrix:

We also wish to allow (right) matrix vector multiplication. It is not too different from the implementation of matrix-matrix multiplication. In this instance we are returning a std::vector and also providing a separate vector as a parameter. Upon invocation of the method we create a new result vector that has the same size as the right hand side, rhs . Then we perform a double loop over the elements of the this matrix and assign the result to an element of the result vector. Finally, we return the result vector:

I've added a final matrix method, which is useful for certain numerical linear algebra techniques. Essentially it returns a vector of the diagonal elements of the matrix. Firstly we create the result vector, then assign it the values of the diagonal elements and finally we return the result vector:

The final set of methods to implement are for accessing the individual elements as well as getting the number of rows and columns from the matrix. They're all quite simple in their implementation. They dereference this and then obtain either an individual element or some private member data:

Full Source Implementation

Now that we have described all the methods in full, here is the full source listing for the QSMatrix class:

Using the Matrix Class

We have the full listings for both the matrix header and source, so we can test the methods out with some examples. Here is the main listing showing the matrix addition operator:

Here is the output of the code. We can see that the elements are all valued $3.0$, which is simply the element-wise addition of mat1 and mat2 :

We will make extensive use of this matrix class in our further numerical linear algebra routines, in particular with statistical analysis and finite difference methods.

QSAlpha

Join the QSAlpha research platform that helps fill your strategy research pipeline, diversifies your portfolio and improves your risk-adjusted returns for increased profitability.

Quantcademy

The Quantcademy

Join the Quantcademy membership portal that caters to the rapidly-growing retail quant trader community and learn how to increase your strategy profitability.

Successful Algorithmic Trading

Successful Algorithmic Trading

How to find new trading strategy ideas and objectively assess them for your portfolio using a Python-based backtesting engine.

Advanced Algorithmic Trading

Advanced Algorithmic Trading

How to implement advanced trading strategies using time series analysis, machine learning and Bayesian statistics with R and Python.

Learn C++

21.12 — Overloading the assignment operator

The copy assignment operator (operator=) is used to copy values from one object to another already existing object .

Related content

As of C++11, C++ also supports “Move assignment”. We discuss move assignment in lesson 22.3 -- Move constructors and move assignment .

Copy assignment vs Copy constructor

The purpose of the copy constructor and the copy assignment operator are almost equivalent -- both copy one object to another. However, the copy constructor initializes new objects, whereas the assignment operator replaces the contents of existing objects.

The difference between the copy constructor and the copy assignment operator causes a lot of confusion for new programmers, but it’s really not all that difficult. Summarizing:

  • If a new object has to be created before the copying can occur, the copy constructor is used (note: this includes passing or returning objects by value).
  • If a new object does not have to be created before the copying can occur, the assignment operator is used.

Overloading the assignment operator

Overloading the copy assignment operator (operator=) is fairly straightforward, with one specific caveat that we’ll get to. The copy assignment operator must be overloaded as a member function.

This prints:

This should all be pretty straightforward by now. Our overloaded operator= returns *this, so that we can chain multiple assignments together:

Issues due to self-assignment

Here’s where things start to get a little more interesting. C++ allows self-assignment:

This will call f1.operator=(f1), and under the simplistic implementation above, all of the members will be assigned to themselves. In this particular example, the self-assignment causes each member to be assigned to itself, which has no overall impact, other than wasting time. In most cases, a self-assignment doesn’t need to do anything at all!

However, in cases where an assignment operator needs to dynamically assign memory, self-assignment can actually be dangerous:

First, run the program as it is. You’ll see that the program prints “Alex” as it should.

Now run the following program:

You’ll probably get garbage output. What happened?

Consider what happens in the overloaded operator= when the implicit object AND the passed in parameter (str) are both variable alex. In this case, m_data is the same as str.m_data. The first thing that happens is that the function checks to see if the implicit object already has a string. If so, it needs to delete it, so we don’t end up with a memory leak. In this case, m_data is allocated, so the function deletes m_data. But because str is the same as *this, the string that we wanted to copy has been deleted and m_data (and str.m_data) are dangling.

Later on, we allocate new memory to m_data (and str.m_data). So when we subsequently copy the data from str.m_data into m_data, we’re copying garbage, because str.m_data was never initialized.

Detecting and handling self-assignment

Fortunately, we can detect when self-assignment occurs. Here’s an updated implementation of our overloaded operator= for the MyString class:

By checking if the address of our implicit object is the same as the address of the object being passed in as a parameter, we can have our assignment operator just return immediately without doing any other work.

Because this is just a pointer comparison, it should be fast, and does not require operator== to be overloaded.

When not to handle self-assignment

Typically the self-assignment check is skipped for copy constructors. Because the object being copy constructed is newly created, the only case where the newly created object can be equal to the object being copied is when you try to initialize a newly defined object with itself:

In such cases, your compiler should warn you that c is an uninitialized variable.

Second, the self-assignment check may be omitted in classes that can naturally handle self-assignment. Consider this Fraction class assignment operator that has a self-assignment guard:

If the self-assignment guard did not exist, this function would still operate correctly during a self-assignment (because all of the operations done by the function can handle self-assignment properly).

Because self-assignment is a rare event, some prominent C++ gurus recommend omitting the self-assignment guard even in classes that would benefit from it. We do not recommend this, as we believe it’s a better practice to code defensively and then selectively optimize later.

The copy and swap idiom

A better way to handle self-assignment issues is via what’s called the copy and swap idiom. There’s a great writeup of how this idiom works on Stack Overflow .

The implicit copy assignment operator

Unlike other operators, the compiler will provide an implicit public copy assignment operator for your class if you do not provide a user-defined one. This assignment operator does memberwise assignment (which is essentially the same as the memberwise initialization that default copy constructors do).

Just like other constructors and operators, you can prevent assignments from being made by making your copy assignment operator private or using the delete keyword:

Note that if your class has const members, the compiler will instead define the implicit operator= as deleted. This is because const members can’t be assigned, so the compiler will assume your class should not be assignable.

If you want a class with const members to be assignable (for all members that aren’t const), you will need to explicitly overload operator= and manually assign each non-const member.

guest

Library homepage

  • school Campus Bookshelves
  • menu_book Bookshelves
  • perm_media Learning Objects
  • login Login
  • how_to_reg Request Instructor Account
  • hub Instructor Commons
  • Download Page (PDF)
  • Download Full Book (PDF)
  • Periodic Table
  • Physics Constants
  • Scientific Calculator
  • Reference & Cite
  • Tools expand_more
  • Readability

selected template will load here

This action is not available.

Mathematics LibreTexts

7.6: Matrices and Matrix Operations

  • Last updated
  • Save as PDF
  • Page ID 15091

Learning Objectives

  • Find the sum and difference of two matrices.
  • Find scalar multiples of a matrix.
  • Find the product of two matrices.

Two club soccer teams, the Wildcats and the Mud Cats, are hoping to obtain new equipment for an upcoming season. Table \(\PageIndex{1}\) shows the needs of both teams.

A goal costs \($300\); a ball costs \($10\); and a jersey costs \($30\). How can we find the total cost for the equipment needed for each team? In this section, we discover a method in which the data in the soccer equipment table can be displayed and used for calculating other information. Then, we will be able to calculate the cost of the equipment.

CNX_Precalc_Figure_09_05_001n.jpg

Finding the Sum and Difference of Two Matrices

To solve a problem like the one described for the soccer teams, we can use a matrix, which is a rectangular array of numbers. A row in a matrix is a set of numbers that are aligned horizontally. A column in a matrix is a set of numbers that are aligned vertically. Each number is an entry, sometimes called an element, of the matrix. Matrices (plural) are enclosed in [ ] or ( ), and are usually named with capital letters. For example, three matrices named \(A\), \(B\), and \(C\) are shown below.

\[ \begin{align*} A&=\begin{bmatrix} 1& 2 \\ 3 & 4 \\ \end{bmatrix} \\[4pt] B &=\begin{bmatrix} 1 & 2 & 7 \\ 0 & -5 & 6 \\ 7 & 8 & 2 \end{bmatrix} \\[4pt] C &=\begin{bmatrix} -1 & 3 \\ 0 & 2 \\ 3 & 1 \end{bmatrix} \end{align*}\]

A matrix is often referred to by its size or dimensions: \(m×n\) indicating \(m\) rows and \(n\) columns. Matrix entries are defined first by row and then by column. For example, to locate the entry in matrix \(A\) identified as \(a_{ij}\),we look for the entry in row \(i\),column \(j\). In matrix \(A\), shown below, the entry in row \(2\), column \(3\) is \(a_{23}\).

\[A=\begin{bmatrix} a_{11} & a_{12} & a_{13} \\a_{21} & a_{22} & a_{23} \\a_{31} & a_{32} & a_{33} \end{bmatrix} \nonumber\]

  • A square matrix is a matrix with dimensions \(n × n\), meaning that it has the same number of rows as columns. The \(3×3\) matrix above is an example of a square matrix.
  • A row matrix is a matrix consisting of one row with dimensions \(1 × n\). \[\begin{bmatrix} a_{11} & a_{12} & a_{13} \end{bmatrix} \nonumber\]
  • A column matrix is a matrix consisting of one column with dimensions \(m × 1\). \[\begin{bmatrix} a_{11} \\ a_{21} \\a_{31} \end{bmatrix} \nonumber\]

A matrix may be used to represent a system of equations. In these cases, the numbers represent the coefficients of the variables in the system. Matrices often make solving systems of equations easier because they are not encumbered with variables. We will investigate this idea further in the next section, but first we will look at basic matrix operations .

Definition: MATRICES

A matrix is a rectangular array of numbers that is usually named by a capital letter: \(A\), \(B\), \(C\),and so on. Each entry in a matrix is referred to as \(a_{ij}\),such that \(i\) represents the row and \(j\) represents the column. Matrices are often referred to by their dimensions: \(m × n\) indicating \(m\) rows and \(n\) columns.

Example \(\PageIndex{1}\): Finding the Dimensions of the Given Matrix and Locating Entries

Given matrix \(A\):

  • What are the dimensions of matrix \(A\)?
  • What are the entries at \(a_{31}\) and \(a_{22}\)?

\[A=\begin{bmatrix} 2 & 1 & 0\\2 & 4 & 7\\3 & 1 & −2 \end{bmatrix} \nonumber\]

  • The dimensions are \(3 \times 3\) because there are three rows and three columns.
  • Entry \(a_{31}\) is the number at row 3, column 1, which is \(3\). The entry \(a_{22}\) is the number at row 2, column 2, which is \(4\). Remember, the row comes first, then the column.

Adding and Subtracting Matrices

We use matrices to list data or to represent systems. Because the entries are numbers, we can perform operations on matrices. We add or subtract matrices by adding or subtracting corresponding entries. To do this, the entries must correspond. Therefore, addition and subtraction of matrices is only possible when the matrices have the same dimensions . We can add or subtract a \(3 \times 3\) matrix and another \(3 \times 3\) matrix, but we cannot add or subtract a \(2 \times 3\) matrix and a \(3 \times 3\) matrix because some entries in one matrix will not have a corresponding entry in the other matrix.

ADDING AND SUBTRACTING MATRICES

Given matrices \(A\) and \(B\) of like dimensions, addition and subtraction of \(A\) and \(B\) will produce matrix \(C\) or matrix \(D\) of the same dimension.

such that \(a_{ij}+b_{ij}=c_{ij}\)

\[A−B=D\]

such that \(a_{ij}−b_{ij}=d_{ij}\)

Matrix addition is commutative .

\[A+B=B+A\]

It is also associative .

\[(A+B)+C=A+(B+C)\]

Example \(\PageIndex{2A}\): Finding the Sum of Matrices

Find the sum of \(A\) and \(B\), given

\[A=\begin{bmatrix}a & b\\c & d \end{bmatrix} \nonumber\]

\[B=\begin{bmatrix}e & f\\g & h\end{bmatrix} \nonumber\]

Add corresponding entries.

\[\begin{align} A+B &=\begin{bmatrix}a & b\\c & d\end{bmatrix}+\begin{bmatrix}e & f\\g & h\end{bmatrix} \nonumber \\[4pt] &=\begin{bmatrix}a+e & b+f\\c+g & d+h \end{bmatrix} \nonumber \end{align} \nonumber\]

Example \(\PageIndex{2B}\): Adding Matrix \(A\) and Matrix \(B\)

Find the sum of \(A\) and \(B\).

\[A=\begin{bmatrix}4 &1\\3 & 2 \end{bmatrix} \nonumber\]

\[B=\begin{bmatrix}5 & 9\\0 & 7\end{bmatrix} \nonumber\]

Add corresponding entries. Add the entry in row 1, column 1, \(a_{11}\), of matrix \(A\) to the entry in row 1, column 1, \(b_{11}\), of \(B\). Continue the pattern until all entries have been added.

\[\begin{align} A+B &=\begin{bmatrix}4&1\\3 &2\end{bmatrix}+\begin{bmatrix}5&9\\0&7\end{bmatrix} \nonumber \\[4pt] &=\begin{bmatrix}4+5&1+9\\3+0&2+7\end{bmatrix} \nonumber \\[4pt] &=\begin{bmatrix}9&10\\3&9\end{bmatrix} \nonumber \end{align} \nonumber\]

Example \(\PageIndex{2C}\): Finding the Difference of Two Matrices

Find the difference of \(A\) and \(B\).

\(A=\begin{bmatrix}−2&3\\0&1\end{bmatrix}\) and \(B=\begin{bmatrix}8&1\\5&4\end{bmatrix}\)

We subtract the corresponding entries of each matrix.

\[\begin{align} A−B &=\begin{bmatrix}−2&3\\0&1\end{bmatrix}−\begin{bmatrix}8&1\\5&4\end{bmatrix} \nonumber \\[4pt] &= \begin{bmatrix}−2−8&3−1\\0−5&1−4\end{bmatrix} \nonumber \\[4pt] &= \begin{bmatrix}−10&2\\−5&−3\end{bmatrix} \nonumber \end{align} \nonumber\]

Example \(\PageIndex{2D}\): Finding the Sum and Difference of Two 3 x 3 Matrices

Given \(A\) and \(B\):

  • Find the sum.
  • Find the difference.

\[A=\begin{bmatrix}2&−10&−2\\14&12&10\\4&−2&2\end{bmatrix} \nonumber\]

\[B=\begin{bmatrix}6&10&−2\\0&−12&−4\\−5&2&−2\end{bmatrix} \nonumber\]

  • Add the corresponding entries.

\[\begin{align} A+B & =\begin{bmatrix} 2& −10& −2\\14 & 12 & 10\\4 & −2 & 2\end{bmatrix}+\begin{bmatrix}6 & 10 & −2\\0 & −12 & −4\\−5 & 2 & −2\end{bmatrix} \nonumber \\[4pt] &=\begin{bmatrix}2+6 & −10+10 & −2−2\\14+0 & 12−12 & 10−4\\4−5 & −2+2 & 2−2\end{bmatrix} \nonumber \\[4pt] &=\begin{bmatrix} 8 & 0 & −4\\14 & 0 & 6\\−1 & 0 & 0\end{bmatrix} \nonumber \end{align} \nonumber\]

  • Subtract the corresponding entries.

\[\begin{align} A−B &=\begin{bmatrix}2&−10&−2\\14&12&10\\4&−2&2\end{bmatrix}−\begin{bmatrix}6&10&−2\\0&−12&−4\\−5&2&−2\end{bmatrix} \nonumber \\[4pt] &=\begin{bmatrix}2−6 & −10−10 & −2+2\\14−0 & 12+12 & 10+4\\4+5 & −2−2 & 2+2\end{bmatrix} \nonumber \\[4pt] &=\begin{bmatrix}−4 & −20 & 0\\14 & 24 & 14\\9 & −4 & 4\end{bmatrix} \nonumber \end{align} \nonumber\]

Exercise \(\PageIndex{1}\)

Add matrix \(A\) and matrix \(B\).

\[A=\begin{bmatrix}2&6\\1&0\\1&−3\end{bmatrix} \nonumber\]

\[B=\begin{bmatrix}3&−2\\1&5\\−4&3\end{bmatrix} \nonumber\]

\[\begin{align} A+B&=\begin{bmatrix}2&6\\ 1 &0\\1&−3\end{bmatrix}+\begin{bmatrix} 3&-2 \\1&5 \\-4&3\end{bmatrix} \nonumber \\[4pt] &=\begin{bmatrix}2+3&6+(−2)\\1+1&0+5\\1+(-4)&−3+3\end{bmatrix} \nonumber \\[4pt] &= \begin{bmatrix}5&4\\2&5\\-3&0\end{bmatrix} \nonumber \end{align} \nonumber\]

Finding Scalar Multiples of a Matrix

Besides adding and subtracting whole matrices, there are many situations in which we need to multiply a matrix by a constant called a scalar. Recall that a scalar is a real number quantity that has magnitude, but not direction. For example, time, temperature, and distance are scalar quantities. The process of scalar multiplication involves multiplying each entry in a matrix by a scalar. A scalar multiple is any entry of a matrix that results from scalar multiplication.

Consider a real-world scenario in which a university needs to add to its inventory of computers, computer tables, and chairs in two of the campus labs due to increased enrollment. They estimate that \(15%\) more equipment is needed in both labs. The school’s current inventory is displayed in Table \(\PageIndex{2}\).

Converting the data to a matrix, we have

\[C_{2013}=\begin{bmatrix}15 & 27\\16&34\\16&34\end{bmatrix} \nonumber\]

To calculate how much computer equipment will be needed, we multiply all entries in matrix \(C\) by \(0.15\).

\[(0.15)C_{2013}=\begin{bmatrix}(0.15)15&(0.15)27\\(0.15)16&(0.15)34\\(0.15)16 &(0.15)34\end{bmatrix}=\begin{bmatrix}2.25 &4.05\\2.4&5.1\\2.4&5.1\end{bmatrix} \nonumber\]

We must round up to the next integer, so the amount of new equipment needed is

\[\begin{bmatrix}3&5\\3&6\\3&6\end{bmatrix} \nonumber\]

Adding the two matrices as shown below, we see the new inventory amounts.

\[\begin{bmatrix}15&27\\16&34\\16&34\end{bmatrix}+\begin{bmatrix}3&5\\3&6\\3&6\end{bmatrix}=\begin{bmatrix}18&32\\19&40\\19&40\end{bmatrix} \nonumber\]

\[C_{2014}=\begin{bmatrix}18&32\\19&40\\19&40\end{bmatrix} \nonumber\]

Thus, Lab A will have \(18\) computers, \(19\) computer tables, and \(19\) chairs; Lab B will have \(32\) computers, \(40\) computer tables, and \(40\) chairs.

SCALAR MULTIPLICATION

Scalar multiplication involves finding the product of a constant by each entry in the matrix. Given

\[A=\begin{bmatrix}a_{11}&a_{12}\\a_{21}&a_{22}\end{bmatrix} \nonumber\]

the scalar multiple \(cA\) is

\[cA=c\begin{bmatrix}a_{11}&a_{12}\\a_{21}&a_{22}\end{bmatrix} \nonumber\]

\[=\begin{bmatrix}ca_{11}&ca_{12}\\ca_{21}&ca_{22}\end{bmatrix} \nonumber\]

Scalar multiplication is distributive. For the matrices \(A\), \(B\),and \(C\) with scalars \(a\) and \(b\),

\[a(A+B)=aA+aB\]

\[(a+b)A=aA+bA\]

Example \(\PageIndex{3}\): Multiplying the Matrix by a Scalar

Multiply matrix \(A\) by the scalar \(3\).

\[A=\begin{bmatrix}8&1\\5&4\end{bmatrix} \nonumber\]

Multiply each entry in \(A\) by the scalar \(3\).

\[ \begin{align} 3A&=3\begin{bmatrix}8&1\\5&4\end{bmatrix} \nonumber \\[4pt] &=\begin{bmatrix}3⋅8&3⋅1\\3⋅5&3⋅4\end{bmatrix} \nonumber \\[4pt] &=\begin{bmatrix}24&3\\15&12\end{bmatrix} \nonumber \end{align} \nonumber\]

Exercise \(\PageIndex{2}\)

Given matrix \(B\), find \(−2B\) where

\[B=\begin{bmatrix}4&1\\3&2\end{bmatrix} \nonumber\]

\[−2B=\begin{bmatrix}−8&−2\\−6&−4\end{bmatrix} \nonumber\]

Example \(\PageIndex{4}\): Finding the Sum of Scalar Multiples

Find the sum \(3A+2B\).

\[A=\begin{bmatrix}1&−2&0\\0&−1&2\\4&3&−6\end{bmatrix} \nonumber\]

\[B=\begin{bmatrix}−1&2&1\\0&−3&2\\0&1&−4\end{bmatrix} \nonumber\]

First, find \(3A\), then \(2B\).

\[ \begin{align} 3A&=\begin{bmatrix}3⋅1&3(−2)&3⋅0\\3⋅0&3(−1)&3⋅2\\3⋅4&3⋅3&3(−6)\end{bmatrix} \nonumber \\[4pt] &=\begin{bmatrix}3&−6&0\\0&−3&6\\12&9&−18\end{bmatrix}\nonumber \end{align} \nonumber\]

\[ \begin{align} 2B&=\begin{bmatrix}2(−1)&2⋅2&2⋅1\\2⋅0&2(−3)&2⋅2\\2⋅0&2⋅1&2(−4)\end{bmatrix} \nonumber \\[4pt] &=\begin{bmatrix}−2&4&2\\0&−6&4\\0&2&−8\end{bmatrix}\nonumber \end{align} \nonumber\]

Now, add \(3A+2B\).

\[ \begin{align} 3A+2B&=\begin{bmatrix}3&−6&0\\0&−3&6\\12&9&−18\end{bmatrix}+\begin{bmatrix}−2&4&2\\0&−6&4\\0&2&−8\end{bmatrix} \nonumber \\[4pt] &=\begin{bmatrix}3−2&−6+4&0+2\\0+0&−3−6&6+4\\12+0&9+2&−18−8\end{bmatrix} \nonumber \\[4pt] &=\begin{bmatrix}1& −2&2\\0&−9&10\\12&11&−26\end{bmatrix} \nonumber \end{align} \nonumber\]

Finding the Product of Two Matrices

In addition to multiplying a matrix by a scalar, we can multiply two matrices. Finding the product of two matrices is only possible when the inner dimensions are the same, meaning that the number of columns of the first matrix is equal to the number of rows of the second matrix. If \(A\) is an \(m × r\) matrix and \(B\) is an \(r × n\) matrix, then the product matrix \(AB\) is an \(m × n\) matrix. For example, the product \(AB\) is possible because the number of columns in \(A\) is the same as the number of rows in \(B\). If the inner dimensions do not match, the product is not defined.

alt

We multiply entries of \(A\) with entries of \(B\) according to a specific pattern as outlined below. The process of matrix multiplication becomes clearer when working a problem with real numbers.

To obtain the entries in row \(i\) of \(AB\), we multiply the entries in row \(i\) of \(A\) by column \(j\) in \(B\) and add. For example, given matrices \(A\) and \(B\), where the dimensions of \(A\) are \(2 \times 3\) and the dimensions of \(B\) are \(3 \times 3\),the product of \(AB\) will be a \(2 \times 3\) matrix.

\[A=\begin{bmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\end{bmatrix} \nonumber \]

\[B=\begin{bmatrix}b_{11}&b_{12}&b_{13}\\b_{21}&b_{22}&b_{23}\\b_{31}&b_{32}&b_{33}\end{bmatrix} \nonumber\]

Multiply and add as follows to obtain the first entry of the product matrix \(AB\).

\[\begin{bmatrix}a_{11}&a_{12}&a_{13}\end{bmatrix} ⋅\begin{bmatrix}b_{11}\\b_{21}\\b_{31}\end{bmatrix}=a_{11}⋅b_{11}+a_{12}⋅b_{21}+a_{13}⋅b_{31} \nonumber \]

\[\begin{bmatrix}a_{11}&a_{12}&a_{13}\end{bmatrix} ⋅\begin{bmatrix}b_{12}\\b_{22}\\b_{32}\end{bmatrix}=a_{11}⋅b_{12}+a_{12}⋅b_{22}+a_{13}⋅b_{32} \nonumber \]

\[\begin{bmatrix}a_{11}&a_{12}&a_{13}\end{bmatrix} ⋅\begin{bmatrix}b_{13}\\b_{23}\\b_{33}\end{bmatrix}=a_{11}⋅b_{13}+a_{12}⋅b_{23}+a_{13}⋅b_{33} \nonumber \]

We proceed the same way to obtain the second row of \(AB\). In other words, row 2 of \(A\) times column 1 of \(B\); row 2 of \(A\) times column 2 of \(B\); row 2 of \(A\) times column 3 of \(B\). When complete, the product matrix will be

\[AB=\begin{bmatrix}a_{11}⋅b_{11}+a_{12}⋅b_{21}+a_{13}⋅b_{31} &a_{11}⋅b_{12}+a_{12}⋅b_{22}+a_{13}⋅b_{32}&a_{11}⋅b_{13}+a_{12}⋅b_{23}+a_{13}⋅b_{33} \\a_{21}⋅b_{11}+a_{22}⋅b_{21}+a_{23}⋅b_{31}&a_{21}⋅b_{12}+a_{22}⋅b_{22}+a_{23}⋅b_{32}&a_{21}⋅b_{13}+a_{22}⋅b_{23}+a_{23}⋅b_{33}\end{bmatrix} \nonumber\]

PROPERTIES OF MATRIX MULTIPLICATION

For the matrice \(A, B\),and \(C\) the following properties hold.

  • Matrix multiplication is associative : \[(AB)C=A(BC).\]
  • Matrix multiplication is distributive : \[C(A+B)=CA+CB\] \[(A+B)C=AC+BC.\]

Note that matrix multiplication is not commutative.

Example \(\PageIndex{5A}\): Multiplying Two Matrices

Multiply matrix \(A\) and matrix \(B\).

\[A=\begin{bmatrix}1&2\\3&4\end{bmatrix} \nonumber\]

\[B=\begin{bmatrix}5&6\\7&8\end{bmatrix} \nonumber\]

First, we check the dimensions of the matrices. Matrix \(A\) has dimensions \(2 × 2\) and matrix \(B\) has dimensions \(2 × 2\). The inner dimensions are the same so we can perform the multiplication. The product will have the dimensions \(2 × 2\).

We perform the operations outlined previously.

alt

Example \(\PageIndex{5B}\): Multiplying Two Matrices

  • Find \(AB\).
  • Find \(BA\).

\[A=\begin{bmatrix}−1&2&3\\ 4&0&5\end{bmatrix} \nonumber\]

\[B=\begin{bmatrix}5&−1\\-4&0\\2&3\end{bmatrix} \nonumber\]

  • As the dimensions of \(A\) are \(2 \times 3\) and the dimensions of \(B\) are \(3 \times 2\),these matrices can be multiplied together because the number of columns in \(A\) matches the number of rows in \(B\). The resulting product will be a \(2 \times 2\) matrix, the number of rows in \(A\) by the number of columns in \(B\).

\[ \begin{align}AB&=\begin{bmatrix}−1&2&3\\4&0&5\end{bmatrix} \begin{bmatrix}5&−1\\−4&0\\2&3\end{bmatrix} \nonumber \\[4pt] &=\begin{bmatrix}−1(5)+2(−4)+3(2)&−1(−1)+2(0)+3(3)\\4(5)+0(−4)+5(2)&4(−1)+0(0)+5(3)\end{bmatrix} \nonumber \\[4pt] &=\begin{bmatrix}−7&10\\30&11\end{bmatrix} \nonumber \end{align} \nonumber\]

  • The dimensions of \(B\) are \(3 \times 2\) and the dimensions of \(A\) are \(2 \times 3\). The inner dimensions match so the product is defined and will be a \(3 \times 3\) matrix.

\[ \begin{align}BA&=\begin{bmatrix}5&−1\\−4&0\\2&3\end{bmatrix} \begin{bmatrix} −1&2&3\\4&0&5\end{bmatrix} \nonumber \\[4pt] &=\begin{bmatrix}5(−1)+−1(4)&5(2)+−1(0)&5(3)+−1(5)\\−4(−1)+0(4)&−4(2)+0(0)&−4(3)+0(5)\\2(−1)+3(4)& 2(2)+3(0)&2(3)+3(5)\end{bmatrix} \nonumber \\[4pt] &=\begin{bmatrix}−9&10&10\\4&−8&−12\\10&4&21\end{bmatrix} \nonumber \end{align} \nonumber\]

Notice that the products \(AB\) and \(BA\) are not equal.

\[AB=\begin{bmatrix}−7&10\\30&11\end{bmatrix}≠ \begin{bmatrix}−9&10&10\\4&−8&−12\\10&4&21\end{bmatrix}=BA \nonumber\]

This illustrates the fact that matrix multiplication is not commutative.

Q&A: Is it possible for AB to be defined but not BA?

Yes, consider a matrix \(A\) with dimension \(3 × 4\) and matrix \(B\) with dimension \(4 × 2\). For the product \(AB\) the inner dimensions are \(4\) and the product is defined, but for the product \(BA\) the inner dimensions are \(2\) and \(3\) so the product is undefined.

Example \(\PageIndex{6}\): Using Matrices in Real-World Problems

Let’s return to the problem presented at the opening of this section. We have Table \(\PageIndex{3}\), representing the equipment needs of two soccer teams.

We are also given the prices of the equipment, as shown in Table \(\PageIndex{4}\).

We will convert the data to matrices. Thus, the equipment need matrix is written as

\[E=\begin{bmatrix}6&10\\30&24\\14&20\end{bmatrix} \nonumber\]

The cost matrix is written as

\[C=\begin{bmatrix}300&10&30\end{bmatrix} \nonumber\]

We perform matrix multiplication to obtain costs for the equipment.

\[ \begin{align} CE&=\begin{bmatrix}300&10&30\end{bmatrix}⋅\begin{bmatrix}6&10\\30&24\\14&20\end{bmatrix} \nonumber \\[4pt] &= \begin{bmatrix}300(6)+10(30)+30(14)&300(10)+10(24)+30(20)\end{bmatrix} \nonumber \\[4pt] &= \begin{bmatrix}2,520&3,840\end{bmatrix} \nonumber \end{align} \nonumber\]

The total cost for equipment for the Wildcats is \($2,520\), and the total cost for equipment for the Mud Cats is \($3,840\).

How to: Given a matrix operation, evaluate using a calculator

  • Save each matrix as a matrix variable \([A], [B], [C],...\)
  • Enter the operation into the calculator, calling up each matrix variable as needed.
  • If the operation is defined, the calculator will present the solution matrix; if the operation is undefined, it will display an error message.

Example \(\PageIndex{7}\): Using a Calculator to Perform Matrix Operations

Find \(AB−C\) given

\(A=\begin{bmatrix}−15&25&32\\41&−7&−28\\10&34&−2\end{bmatrix}\), \(B=\begin{bmatrix}45&21&−37\\−24&52&19\\6&−48&−31\end{bmatrix}\), and \(C=\begin{bmatrix}−100&−89&−98\\25&−56&74\\−67&42&−75\end{bmatrix}\)

On the matrix page of the calculator, we enter matrix \(A\) above as the matrix variable \([ A ]\), matrix \(B\) above as the matrix variable \([ B ]\), and matrix \(C\) above as the matrix variable \([ C ]\).

On the home screen of the calculator, we type in the problem and call up each matrix variable as needed.

\[[A]×[B]−[C] \nonumber\]

The calculator gives us the following matrix.

\[\begin{bmatrix}−983&−462&136\\1,820&1,897&−856\\−311&2,032&413\end{bmatrix} \nonumber\]

Access these online resources for additional instruction and practice with matrices and matrix operations.

  • Dimensions of a Matrix
  • Matrix Addition and Subtraction
  • Matrix Operations
  • Matrix Multiplication

Key Concepts

  • A matrix is a rectangular array of numbers. Entries are arranged in rows and columns.
  • The dimensions of a matrix refer to the number of rows and the number of columns. A \(3×2\) matrix has three rows and two columns. See Example \(\PageIndex{1}\).
  • We add and subtract matrices of equal dimensions by adding and subtracting corresponding entries of each matrix. See Example \(\PageIndex{2}\), Example \(\PageIndex{3}\), Example \(\PageIndex{4}\), and Example \(\PageIndex{5}\).
  • Scalar multiplication involves multiplying each entry in a matrix by a constant. See Example \(\PageIndex{6}\).
  • Scalar multiplication is often required before addition or subtraction can occur. See Example \(\PageIndex{7}\).
  • Multiplying matrices is possible when inner dimensions are the same—the number of columns in the first matrix must match the number of rows in the second.
  • The product of two matrices, \(A\) and \(B\),is obtained by multiplying each entry in row 1 of \(A\) by each entry in column 1 of \(B\); then multiply each entry of row 1 of \(A\) by each entry in columns 2 of \(B\),and so on. See Example \(\PageIndex{8}\) and Example \(\PageIndex{9}\).
  • Many real-world problems can often be solved using matrices. See Example \(\PageIndex{10}\).
  • We can use a calculator to perform matrix operations after saving each matrix as a matrix variable. See Example \(\PageIndex{11}\).

cppreference.com

Copy assignment operator.

A copy assignment operator is a non-template non-static member function with the name operator = that can be called with an argument of the same class type and copies the content of the argument without mutating the argument.

[ edit ] Syntax

For the formal copy assignment operator syntax, see function declaration . The syntax list below only demonstrates a subset of all valid copy assignment operator syntaxes.

[ edit ] Explanation

The copy assignment operator is called whenever selected by overload resolution , e.g. when an object appears on the left side of an assignment expression.

[ edit ] Implicitly-declared copy assignment operator

If no user-defined copy assignment operators are provided for a class type, the compiler will always declare one as an inline public member of the class. This implicitly-declared copy assignment operator has the form T & T :: operator = ( const T & ) if all of the following is true:

  • each direct base B of T has a copy assignment operator whose parameters are B or const B & or const volatile B & ;
  • each non-static data member M of T of class type or array of class type has a copy assignment operator whose parameters are M or const M & or const volatile M & .

Otherwise the implicitly-declared copy assignment operator is declared as T & T :: operator = ( T & ) .

Due to these rules, the implicitly-declared copy assignment operator cannot bind to a volatile lvalue argument.

A class can have multiple copy assignment operators, e.g. both T & T :: operator = ( T & ) and T & T :: operator = ( T ) . If some user-defined copy assignment operators are present, the user may still force the generation of the implicitly declared copy assignment operator with the keyword default . (since C++11)

The implicitly-declared (or defaulted on its first declaration) copy assignment operator has an exception specification as described in dynamic exception specification (until C++17) noexcept specification (since C++17)

Because the copy assignment operator is always declared for any class, the base class assignment operator is always hidden. If a using-declaration is used to bring in the assignment operator from the base class, and its argument type could be the same as the argument type of the implicit assignment operator of the derived class, the using-declaration is also hidden by the implicit declaration.

[ edit ] Implicitly-defined copy assignment operator

If the implicitly-declared copy assignment operator is neither deleted nor trivial, it is defined (that is, a function body is generated and compiled) by the compiler if odr-used or needed for constant evaluation (since C++14) . For union types, the implicitly-defined copy assignment copies the object representation (as by std::memmove ). For non-union class types, the operator performs member-wise copy assignment of the object's direct bases and non-static data members, in their initialization order, using built-in assignment for the scalars, memberwise copy-assignment for arrays, and copy assignment operator for class types (called non-virtually).

[ edit ] Deleted copy assignment operator

An implicitly-declared or explicitly-defaulted (since C++11) copy assignment operator for class T is undefined (until C++11) defined as deleted (since C++11) if any of the following conditions is satisfied:

  • T has a non-static data member of a const-qualified non-class type (or possibly multi-dimensional array thereof).
  • T has a non-static data member of a reference type.
  • T has a potentially constructed subobject of class type M (or possibly multi-dimensional array thereof) such that the overload resolution as applied to find M 's copy assignment operator
  • does not result in a usable candidate, or
  • in the case of the subobject being a variant member , selects a non-trivial function.

[ edit ] Trivial copy assignment operator

The copy assignment operator for class T is trivial if all of the following is true:

  • it is not user-provided (meaning, it is implicitly-defined or defaulted);
  • T has no virtual member functions;
  • T has no virtual base classes;
  • the copy assignment operator selected for every direct base of T is trivial;
  • the copy assignment operator selected for every non-static class type (or array of class type) member of T is trivial.

A trivial copy assignment operator makes a copy of the object representation as if by std::memmove . All data types compatible with the C language (POD types) are trivially copy-assignable.

[ edit ] Eligible copy assignment operator

Triviality of eligible copy assignment operators determines whether the class is a trivially copyable type .

[ edit ] Notes

If both copy and move assignment operators are provided, overload resolution selects the move assignment if the argument is an rvalue (either a prvalue such as a nameless temporary or an xvalue such as the result of std::move ), and selects the copy assignment if the argument is an lvalue (named object or a function/operator returning lvalue reference). If only the copy assignment is provided, all argument categories select it (as long as it takes its argument by value or as reference to const, since rvalues can bind to const references), which makes copy assignment the fallback for move assignment, when move is unavailable.

It is unspecified whether virtual base class subobjects that are accessible through more than one path in the inheritance lattice, are assigned more than once by the implicitly-defined copy assignment operator (same applies to move assignment ).

See assignment operator overloading for additional detail on the expected behavior of a user-defined copy-assignment operator.

[ edit ] Example

[ edit ] defect reports.

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

[ edit ] See also

  • converting constructor
  • copy constructor
  • copy elision
  • default constructor
  • aggregate initialization
  • constant initialization
  • copy initialization
  • default initialization
  • direct initialization
  • initializer list
  • list initialization
  • reference initialization
  • value initialization
  • zero initialization
  • move assignment
  • move constructor
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 2 February 2024, at 15:13.
  • This page has been accessed 1,333,785 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

Learn C++ practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn c++ interactively, introduction to c++.

  • Getting Started With C++
  • Your First C++ Program

C++ Fundamentals

  • C++ Comments
  • C++ Variables, Literals and Constants
  • C++ Data Types
  • C++ Type Modifiers
  • C++ Constants
  • C++ Basic Input/Output
  • C++ Operators

Flow Control

  • C++ Relational and Logical Operators
  • C++ if, if...else and Nested if...else
  • C++ for Loop
  • C++ while and do...while Loop
  • C++ break Statement
  • C++ continue Statement
  • C++ switch..case Statement
  • C++ goto Statement

C++ Ternary Operator

  • C++ Functions
  • C++ User-defined Function Types
  • C++ Programming Default Arguments

C++ Function Overloading

  • C++ Inline Functions
  • C++ Recursion

Arrays and Strings

  • Passing Array to a Function in C++ Programming
  • C++ Multidimensional Arrays
  • C++ String Class

Pointers and References

  • C++ Pointers
  • C++ Pointers and Arrays
  • C++ References
  • C++ Pass by Reference
  • C++ Return by Reference
  • C++ Memory Management: new and delete

Structures and Enumerations

  • C++ Structures
  • C++ Structure and Function
  • C++ Pointers to Structure
  • C++ Enumeration

Object Oriented Programming I

  • C++ Classes and Objects
  • C++ Constructors and Destructors
  • C++ Access Modifiers
  • C++ Encapsulation
  • C++ Inheritance
  • C++ Public, Protected and Private Inheritance
  • C++ Multiple, Multilevel and Hierarchical Inheritance
  • C++ Pass and return object from C++ Functions
  • C++ friend Function and friend Classes

C++ Polymorphism

  • C++ Shadowing Base Class Member Function
  • C++ Virtual Functions and Function Overriding
  • C++ Abstract Class and Pure Virtual Function

OOP - Overloading

  • C++ Constructor Overloading

C++ Operator Overloading

Standard template library (stl) i.

  • C++ Standard Template Library
  • C++ STL Containers
  • C++ std::array
  • C++ Vectors
  • C++ Forward List
  • C++ Priority Queue

Standard Template Library (STL) II

  • C++ Multimap
  • C++ Multiset
  • C++ Unordered Map
  • C++ Unordered Set
  • C++ Unordered Multiset
  • C++ Unordered Multimap

Standard Template Library (STL) III

  • C++ Iterators
  • C++ Algorithm
  • C++ Functor

Advanced Topics I

  • C++ Exceptions Handling
  • C++ File Handling
  • C++ Ranged for Loop
  • C++ Nested Loop
  • C++ Bitwise Operators
  • C++ Function Template
  • C++ Class Templates
  • C++ Type Conversion
  • C++ Type Conversion Operators

Advanced Topics II

  • C++ Namespaces
  • C++ Preprocessors and Macros
  • C++ Storage Class
  • C++ Buffers
  • C++ istream
  • C++ ostream

C++ Tutorials

  • Subtract Complex Number Using Operator Overloading
  • Increment ++ and Decrement -- Operator Overloading in C++ Programming
  • Add Complex Numbers by Passing Structure to a Function

C++ Operator Precedence and Associativity

In C++, we can define how operators behave for user-defined types like class and structures For example,

The + operator, when used with values of type int , returns their sum. However, when used with objects of a user-defined type, it is an error.

In this case, we can define the behavior of the + operator to work with objects as well.

This concept of defining operators to work with objects and structure variables is known as operator overloading .

  • Syntax for C++ Operator Overloading

The syntax for overloading an operator is similar to that of function with the addition of the operator keyword followed by the operator symbol.

  • returnType - the return type of the function
  • operator - a special keyword
  • symbol - the operator we want to overload ( + , < , - , ++ , etc.)
  • arguments - the arguments passed to the function
  • Overloading the Binary + Operator

Following is a program to demonstrate the overloading of the + operator for the class Complex .

Here, we first created a friend function with a return type Complex .

The operator keyword followed by + indicates that we are overloading the + operator.

The function takes two arguments:

  • Complex& indicates that we are passing objects by reference and obj1 and obj2 are references to Complex objects. This is an efficient approach because it avoids unnecessary copying, especially for large objects. To learn more, visit C++ References .
  • const indicates that referenced objects are constant, meaning we cannot modify obj1 and obj2 within the function.

Inside the function, we created another Complex object, temp to store the result of addition.

We then add the real parts of two objects and store it into the real attribute of the temp object.

Similarly, we add the imaginary parts of the two objects and store them into the img attribute of the temp object.

At last, we return the temp object from the function.

We can also overload the operators using a member function instead of a friend function. For example,

In this case, the operator is invoked by the first operand. Meaning, the line

translates to

Here, the number of arguments to the operator function is reduced by one because the first argument is used to invoke the function.

The problem with this approach is, not all the time the first operand is an object of a user-defined type. For example:

That's why it is recommended to overload operator functions as a non-member function generally, defined as a friend function.

  • Overloading ++ as a Prefix Operator

Following is a program to demonstrate the overloading of the ++ operator for the class Count .

Here, when we use ++count1; , the void operator ++ () is called. This increases the value attribute for the object count1 by 1.

Note : When we overload operators, we can use it to work in any way we like. For example, we could have used ++ to increase value by 100.

However, this makes our code confusing and difficult to understand. It's our job as a programmer to use operator overloading properly and in a consistent and intuitive way.

To overload the ++ operator as a Postfix Operator, we declare a member function operator++() with one argument having type int .

Here, when we use count1++; , the void operator ++ (int) is called. This increments the value attribute for the object count1 by 1.

Note : The argument int is just to indicate that the operator is used as a postfix operator.

  • Things to Remember in C++ Operator Overloading

1. By default, operators = and & are already overloaded in C++. For example,

we can directly use the = operator to copy objects of the same class. Here, we do not need to create an operator function.

2. We cannot change the precedence and associativity of operators using operator overloading.

3. We cannot overload following operators in C++:

  • :: (scope resolution)
  • . (member selection)
  • .* (member selection through pointer to function)
  • ?: (ternary operator)
  • sizeof operator
  • typeid Operator

4. We cannot overload operators for fundamental data types like int , float , etc

  • How to overload increment operator in right way?
  • How to overload binary operator - to subtract complex numbers?
  • Increment ++ and Decrement -- Operators

Table of Contents

  • Introduction

Sorry about that.

Related Tutorials

C++ Tutorial

CS11 Intro C++ Lab 6: Integer Matrix

This assignment is your first foray into heap memory allocation in C++. As discussed in class, you should generally avoid having to explicitly manage heap memory allocations yourself; you should usually prefer to rely on classes that take care of this responsibility for you, unless it made a lot of sense to do it yourself. But, in order to learn more of the nitty gritty details of C++, we will write a C++ Matrix class that implements a 2D integer matrix, dynamically allocating a 1D array of memory from the heap to store the matrix data. Your Matrix should be declared in matrix.h , and any definitions can go into matrix.cpp . You should feel free to define functions in the class declaration, partly because it facilitates inlining of your functions, and partly because it makes your code more streamlined.

Note that the elements are integers, not floats or some other type. We are keeping it simple this week!

Provide these constructors:

  • Matrix{int rows, int cols} initializes a rows x cols matrix where all elements are set to 0. The rows and cols values must be positive, or an invalid_argument exception should be thrown.
  • Matrix{} initializes a 0x0 matrix.

Since your Matrix class dynamically allocates memory, you need to provide non-default implementations of these operations:

  • Matrix copy-constructor
  • Matrix copy-assignment operator
  • Matrix destructor

This is an example of the Rule of Three: If your class requires a user-defined destructor, a user-defined copy-constructor, or a user-defined copy-assignment operator, it almost certainly requires all three.

When you implement the above operations, you should think carefully about avoiding code duplication. Most of the operations that would be duplicated are pretty short, so it isn't the most serious problem, but a good programmer always tries to minimize code duplication.

Other Operations

You should additionally provide these operations. Note that we are not specifying where you should use the const keyword and pass-by-reference semantics, because you should be learning these rules yourself. When we review your submission, we will point out places in your code where corrections need to be made to follow best practices.

  • int numRows() returns the total number of rows

int numCols() returns the total number of columns

  • int get(int r, int c) returns the value stored at the specified row and column. This member function should throw an invalid_argument exception if the row or column index is out of bounds

int set(int r, int c, int value) sets the value stored at the specified row and column. Again, this member function should throw an invalid_argument exception if the row or column index is out of bounds

Finally, we would like to be able to compare whether two matrix objects have the same values or not, so you should implement the == and != operators for your Matrix class. These operators can be implemented as either member operator overloads or nonmember operator overloads; this week you should implement them as member operator overloads. The reason is that it's shorter and likely more efficient to iterate over the internal 1D arrays directly, which you will be able to do from inside the member functions. If you implement nonmember operator overloads, you will have to call the above accessors, and it will be more complicated.

bool operator==(Matrix m) should return true iff the specified matrix is "equal to" this matrix; i.e. the total number of rows and columns are identical, and all of the values are also identical

(Don't forget that you must use const and pass-by-reference where appropriate!)

bool operator!=(Matrix m) should do the opposite of operator==() . (Hint, hint!)

Coding Style

Comment your class thoroughly in the Doxygen style, including a class-level description, and a comment for every data-member and member-function. (Comments may be brief if the function's purpose is obvious, but you must still comment all of these things.)

You do not need to create a Doxyfile or run Doxygen this time, as long as you follow the Doxygen format properly.

Make sure to always identify what arguments are illegal. Additionally, always document any exceptions that may be thrown, and the circumstances that would cause them to be thrown.

A test suite for your class is provided here ; make sure to fix any test failures you encounter.

Build Automation

As before, write a Makefile for your project that builds and tests your Matrix code.

The all target should build the test binary, but not run it.

The test target should run the test binary.

The clean target should delete .o files and binaries. As always, make sure to back up your code before testing your clean target for the first time!

Make sure all files are compiled with the -Wall and -Werror arguments (these will go in your CXXFLAGS variable) so that any malformed but otherwise legal code is identified by the compiler.

Submitting Your Work

Once you have completed the above tasks, submit your work through csman. Make sure to submit these files:

  • matrix.cpp (if present)

You do not need to submit the test code; we will test your program with a fresh copy of these files.

Assignment Feedback Survey

Please also complete and submit a feedback survey with your submission, telling us about your experience with this assignment. Doing so will help us to improve CS11 Intro C++ in the future.

Copyright © 2019 by California Institute of Technology. All rights reserved. Generated from cpp-lab6.md .

  • C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management

Assignment Operators In C++

  • Move Assignment Operator in C++ 11
  • JavaScript Assignment Operators
  • Assignment Operators in Programming
  • Is assignment operator inherited?
  • Solidity - Assignment Operators
  • Augmented Assignment Operators in Python
  • bitset operator[] in C++ STL
  • C++ Assignment Operator Overloading
  • Self assignment check in assignment operator
  • Copy Constructor vs Assignment Operator in C++
  • Operators in C++
  • C++ Arithmetic Operators
  • Bitwise Operators in C++
  • Casting Operators in C++
  • Assignment Operators in C
  • Assignment Operators in Python
  • Compound assignment operators in Java
  • Arithmetic Operators in C
  • Operators in C
  • Vector in C++ STL
  • Initialize a vector in C++ (7 different ways)
  • Map in C++ Standard Template Library (STL)
  • std::sort() in C++ STL
  • Inheritance in C++
  • The C++ Standard Template Library (STL)
  • Object Oriented Programming in C++
  • C++ Classes and Objects
  • Virtual Function in C++
  • Set in C++ Standard Template Library (STL)

In C++, the assignment operator forms the backbone of many algorithms and computational processes by performing a simple operation like assigning a value to a variable. It is denoted by equal sign ( = ) and provides one of the most basic operations in any programming language that is used to assign some value to the variables in C++ or in other words, it is used to store some kind of information.

The right-hand side value will be assigned to the variable on the left-hand side. The variable and the value should be of the same data type.

The value can be a literal or another variable of the same data type.

Compound Assignment Operators

In C++, the assignment operator can be combined into a single operator with some other operators to perform a combination of two operations in one single statement. These operators are called Compound Assignment Operators. There are 10 compound assignment operators in C++:

  • Addition Assignment Operator ( += )
  • Subtraction Assignment Operator ( -= )
  • Multiplication Assignment Operator ( *= )
  • Division Assignment Operator ( /= )
  • Modulus Assignment Operator ( %= )
  • Bitwise AND Assignment Operator ( &= )
  • Bitwise OR Assignment Operator ( |= )
  • Bitwise XOR Assignment Operator ( ^= )
  • Left Shift Assignment Operator ( <<= )
  • Right Shift Assignment Operator ( >>= )

Lets see each of them in detail.

1. Addition Assignment Operator (+=)

In C++, the addition assignment operator (+=) combines the addition operation with the variable assignment allowing you to increment the value of variable by a specified expression in a concise and efficient way.

This above expression is equivalent to the expression:

2. Subtraction Assignment Operator (-=)

The subtraction assignment operator (-=) in C++ enables you to update the value of the variable by subtracting another value from it. This operator is especially useful when you need to perform subtraction and store the result back in the same variable.

3. Multiplication Assignment Operator (*=)

In C++, the multiplication assignment operator (*=) is used to update the value of the variable by multiplying it with another value.

4. Division Assignment Operator (/=)

The division assignment operator divides the variable on the left by the value on the right and assigns the result to the variable on the left.

5. Modulus Assignment Operator (%=)

The modulus assignment operator calculates the remainder when the variable on the left is divided by the value or variable on the right and assigns the result to the variable on the left.

6. Bitwise AND Assignment Operator (&=)

This operator performs a bitwise AND between the variable on the left and the value on the right and assigns the result to the variable on the left.

7. Bitwise OR Assignment Operator (|=)

The bitwise OR assignment operator performs a bitwise OR between the variable on the left and the value or variable on the right and assigns the result to the variable on the left.

8. Bitwise XOR Assignment Operator (^=)

The bitwise XOR assignment operator performs a bitwise XOR between the variable on the left and the value or variable on the right and assigns the result to the variable on the left.

9. Left Shift Assignment Operator (<<=)

The left shift assignment operator shifts the bits of the variable on the left to left by the number of positions specified on the right and assigns the result to the variable on the left.

10. Right Shift Assignment Operator (>>=)

The right shift assignment operator shifts the bits of the variable on the left to the right by a number of positions specified on the right and assigns the result to the variable on the left.

Also, it is important to note that all of the above operators can be overloaded for custom operations with user-defined data types to perform the operations we want.

Please Login to comment...

Similar reads.

  • Geeks Premier League 2023
  • Geeks Premier League

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Assignment Operators in C » PREP INSTA

    matrix assignment operator c

  2. Assignment Operators in C

    matrix assignment operator c

  3. Assignment Operators in C

    matrix assignment operator c

  4. Assignment Operators in C++

    matrix assignment operator c

  5. [100% Working Code]

    matrix assignment operator c

  6. Assignment Operators in C++

    matrix assignment operator c

VIDEO

  1. assignment Operator C Language in Telugu

  2. Z to A letters in matrix in C Language || Simple Method Apply

  3. Augmented assignment operators in C

  4. Assignment Operator in C Programming

  5. Assignment Operator│C programming│Part# 15│Learn CSE Malayalam

  6. Intro Year 9 History Matrix Assignment Breakdown

COMMENTS

  1. c++ matrix class: overloading assignment operator

    friend Matrix& Matrix::operator=(const Matrix& m); This above part makes little sense since operator= must be defined as a member function within the class.. Actually I think your life would be a lot easier if you avoided the need for friends here (or at least so many of them).

  2. Matrix operations using operator overloading

    Using Operator Overloading M1 [] [] and M2 [] [] can be added as M1 * M2 . In the above statement M1 is treated hai global and M2 [] [] is passed as an argument to the function "void Matrix::operator* (Matrix x) ". In the above overloaded function, the approach for multiplication of two matrix is implemented by treating M1 [] [] as first ...

  3. Matrix assignment operator

    Matrix assignment operator . Matrix assignment operator. Stefanyco. I am trying to overload the assignment operator. My code is to multiply, add, and multiply matrices, but as I am doing this step by step, I am not able to successfully overload this operator and I do not understand why. I know there is something I am overlooking but I can't see it.

  4. The Assignment Operator

    In C++, the assignment operator (and many other operators) is a function call The following expressions are equivalent in C++: x = expression; ... You will see that Matrix B points to the same matrix as Matrix A . When the default assignment operator is inadequate , we must define our own assignment operator and replace the C++'s provided ...

  5. Assignment operators

    for assignments to class type objects, the right operand could be an initializer list only when the assignment is defined by a user-defined assignment operator. removed user-defined assignment constraint. CWG 1538. C++11. E1 ={E2} was equivalent to E1 = T(E2) ( T is the type of E1 ), this introduced a C-style cast. it is equivalent to E1 = T{E2}

  6. Matrix Classes in C++

    There are two types of operators to be overloaded here. The first is operation without assignment. The second is operation with assignment. The first type of operator method creates a new matrix to store the result of an operation (such as addition), while the second type applies the result of the operation into the left-hand argument.

  7. Assignment Operators in C

    1. "=": This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example: a = 10; b = 20; ch = 'y'; 2. "+=": This operator is combination of '+' and '=' operators. This operator first adds the current value of the variable on left to the value on the right and ...

  8. 21.12

    21.12 — Overloading the assignment operator. The copy assignment operator (operator=) is used to copy values from one object to another already existing object. As of C++11, C++ also supports "Move assignment". We discuss move assignment in lesson 22.3 -- Move constructors and move assignment .

  9. C++ operator overloading for matrix operations

    This work assignment in operator overloading .I need to use operators *, [][], =, +, -, << on objects of type matrix for example add to matrix using this code: m=m+s. I already sent the code to my teacher but I still want your opinion so I can improve the next code. matrix.h. #ifndef Matrix_h. #define Matrix_h. #include <iostream>.

  10. Assignment Operators in Programming

    Assignment operators are used in programming to assign values to variables. We use an assignment operator to store and update data within a program. They enable programmers to store data in variables and manipulate that data. The most common assignment operator is the equals sign (=), which assigns the value on the right side of the operator to ...

  11. 7.6: Matrices and Matrix Operations

    A row in a matrix is a set of numbers that are aligned horizontally. A column in a matrix is a set of numbers that are aligned vertically. Each number is an entry, sometimes called an element, of the matrix. Matrices (plural) are enclosed in [ ] or ( ), and are usually named with capital letters. For example, three matrices named A, B, and C ...

  12. Move assignment operator

    The move assignment operator is called whenever it is selected by overload resolution, e.g. when an object appears on the left-hand side of an assignment expression, where the right-hand side is an rvalue of the same or implicitly convertible type.. Move assignment operators typically "steal" the resources held by the argument (e.g. pointers to dynamically-allocated objects, file descriptors ...

  13. Copy assignment operator

    the copy assignment operator selected for every non-static class type (or array of class type) member of T is trivial. A trivial copy assignment operator makes a copy of the object representation as if by std::memmove. All data types compatible with the C language (POD types) are trivially copy-assignable.

  14. Overloading Subscript or array index operator [] in C++

    1) Overloading of [] may be useful when we want to check for index out of bound. 2) We must return by reference in function because an expression like "arr [i]" can be used an lvalue. Following is C++ program to demonstrate overloading of array index operator []. CPP. #include <cstdlib>. #include <iostream>.

  15. C++ Operator Overloading (With Examples)

    Program to multiply matrix. Explore C++ Examples Reference Materials. iostream . cmath . cstring . ctime . View all ... Things to Remember in C++ Operator Overloading. 1. By default, operators = and & are already overloaded in C++. For example,

  16. CS11 Intro C++ Lab 6: Integer Matrix

    CS11 Intro C++ Lab 6: Integer Matrix. This assignment is your first foray into heap memory allocation in C++. As discussed in class, you should generally avoid having to explicitly manage heap memory allocations yourself; you should usually prefer to rely on classes that take care of this responsibility for you, unless it made a lot of sense to do it yourself.

  17. c++

    Use a 1D array then. It will be much cleaner and simpler and faster than an array of pointers to arrays... You can do something like: template <typename T> class Matrix { private: // Note: Assuming T is a trivial type, most likely a fundamental type...

  18. c++

    I am implementing assignment operator function for a template matrix class. It should take care of different datatype matrix assignments. eg Integer matrix is assigned to a double matrix. for that i have following declaration: template<class U> MyMatrix<T>& operator= (const MyMatrix<U> &rhs) {...} My problem is, if i implement the fuction ...

  19. Assignment Operators In C++

    In C++, the addition assignment operator (+=) combines the addition operation with the variable assignment allowing you to increment the value of variable by a specified expression in a concise and efficient way. Syntax. variable += value; This above expression is equivalent to the expression: variable = variable + value; Example.