Program To Add Two Matrices By Returning An Object From A Function Using C++

LEVEL: Beginner

Whats in this post?

  1. Code
  2. Output
  3. Background and Explanation of the code

Code


To copy code: Click View Source “View Source” on the right of this code snippet.


Background and Explanation of the code


The above program is used to perform matrix addition by specifying a class matrix that contains private data member a [10] [10], m, n and public member functions read ( ), show ( ) and add ( ).Every object of this class represents a particular matrix with m rows and n columns.So we have defined three objects m1, m2 and m3 where objects m1 and m2 are used for entering two matrices whose addition is later stored in object m3.The statement

m3 = m1.add (m2);

invokes the member function add ( ) using object m1 and pass the object m2 as an argument by value.In the member function add ( ), the data members of object m1 can be accessed simple by name whereas the data members of object m2 can be accessed by its copy mm2 using the dot operator.If the order of two matrices to be added are same, then a local object temp is created in add ( ) that stores the result of addition of two matrices in its data member 2-d array using the dot operator.

The object temp is finally returned to object m3 in main ( ) using return statement .In the main ( ), the statement m3.show ( ); displays the result.

OUTPUT

Enter order of m x n matrix = 2   2

Enter elements : 1  2  3  4

Enter order of m x n matrix = 2   2

Enter elements : 4  3  2  1

On addition we get

5       5         5        5