Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored....

48
Matrices Matrices Introducing Inheritance Introducing Inheritance

Transcript of Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored....

Page 1: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

MatricesMatrices

Introducing InheritanceIntroducing Inheritance

Page 2: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

ConsiderConsider

A A matrixmatrix is a grid in which numbers can be stored. is a grid in which numbers can be stored.

Algorithms for problems in scientific computing frequently store the coefficients for a Algorithms for problems in scientific computing frequently store the coefficients for a system of equations in a matrix, for convenient manipulation.system of equations in a matrix, for convenient manipulation.

A class to represent matrices is thus a useful class for scientific computing.A class to represent matrices is thus a useful class for scientific computing.

1 9 2

8 3 7

4 6 5

Page 3: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

ProblemProblem

Let’s write a program to perform matrix Let’s write a program to perform matrix addition.addition.

1 9 2

8 3 7

4 6 5

1 2 3

4 5 6

7 8 9

2 11 5

12 8 13

11 14 10

+

m1 m2 m3

For simplicity, we will store a matrix’s values in a file.For simplicity, we will store a matrix’s values in a file.

Since there is no predefined Matrix type, we will design Since there is no predefined Matrix type, we will design a a Matrix class... class...

Page 4: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

BehaviorBehaviorOur program should explain its purpose, and prompt for and read the Our program should explain its purpose, and prompt for and read the

values of the first matrix from the keyboard. It should then do the same values of the first matrix from the keyboard. It should then do the same for the second matrix. It should then add the two matrices producing a for the second matrix. It should then add the two matrices producing a third matrix. It should then display the third matrix to the screen.third matrix. It should then display the third matrix to the screen.

Page 5: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

ObjectsObjects

Description Type Kind NameDescription Type Kind Name

1st matrix Matrix varying matrix1

3rd matrix Matrix varying matrix3

screen ostream varying cout

2cd matrix Matrix varying matrix2

keyboard istream varying cin

Page 6: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

OperationsOperations

Description Predefined? Library? NameDescription Predefined? Library? Name

display a string yes string <<

read a matrix no --- >> from istream

add 2 matrices no --- ???

write a matrix no --- ??? to ostream

Page 7: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

AlgorithmAlgorithm0. Display purpose of program0. Display purpose of program1. Prompt for and read 1. Prompt for and read matrix1matrix1 using using cincin..2. Prompt for and read 2. Prompt for and read matrix2matrix2 using using cincin..3. Compute 3. Compute matrix3matrix3 = = matrix1matrix1 + + matrix2matrix2..4. Write 4. Write matrix3matrix3 to to coutcout..

Page 8: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

Coding Our AlgorithmCoding Our AlgorithmIdeally, we want to implement our algorithm this Ideally, we want to implement our algorithm this

way:way:// matAdd.cpp// ... documentation// ... other #includes#include “Matrix.h”

int main(){ cout << “\nTo add two matrices, enter the” << “\n values of the first matrix“ << “\n (one row per line)\n”; Matrix mat1; cin >> mat1;

cout << “\nDo the same for the second matrix:\n”; Matrix mat2; cin >> mat2; // ...

Page 9: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

Coding (Coding (Ct’dCt’d))// ... matAdd.cpp continued

Matrix mat3 = mat1 + mat2;

cout << “\nThe sum of\n” << mat1 << “\n\n and\n\n” << mat2 << “\n\n is\n\n” << mat3 << “\n\n”;}

If we build an easy-to-use Matrix class, writing a program to If we build an easy-to-use Matrix class, writing a program to manipulate matrices can be as easy as writing a program that manipulate matrices can be as easy as writing a program that manipulates integers.manipulates integers.

Page 10: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

AnalysisAnalysisWe have a few function members to define!We have a few function members to define!

Our algorithms requires:Our algorithms requires:– matrix input from an istreammatrix input from an istream

– matrix additionmatrix addition

– matrix output to an ostreammatrix output to an ostream

In addition, we should provide “normal” class operations (normal constructors, accessors) as well as other Matrix operations.In addition, we should provide “normal” class operations (normal constructors, accessors) as well as other Matrix operations.

Page 11: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

DifficultyDifficulty

We could declare our Matrix class as follows:We could declare our Matrix class as follows:class Matrix{ public: // ... private: int myRows, myColumns; typedef vector<double> Row; vector<Row> myGrid;};

However, if we do so, then However, if we do so, then wewe must redefine many of the vector operations must redefine many of the vector operations for our Matrix class, which will greatly increase our development time.for our Matrix class, which will greatly increase our development time.

Page 12: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

For ExampleFor Example

If we take this approach, then we will be unable to use the If we take this approach, then we will be unable to use the subscript operator on a Matrix object:subscript operator on a Matrix object:

Matrix mat1;// ...cout << mat1[0][0] << endl;

The reason is that a Matrix declared using this approach The reason is that a Matrix declared using this approach has-ahas-a vector of vectors as a data member, but such Matrix vector of vectors as a data member, but such Matrix is notis not a vector of vectors. a vector of vectors.

That is, although subscript is an operation defined for class That is, although subscript is an operation defined for class vectorvector, it is not defined for a Matrix unless , it is not defined for a Matrix unless wewe define it (as is the case for all vector define it (as is the case for all vector operations).operations).

Page 13: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

A SolutionA Solution

One way to avoid this problem is to declare our Matrix One way to avoid this problem is to declare our Matrix class as class as an extension toan extension to vector of vectors: vector of vectors:

typedef vector<double> Row;class Matrix : public vector<Row>{ // ...};

This approach tells the compiler that a Matrix This approach tells the compiler that a Matrix is ais a vector< vector<double> >..

Since such a Matrix Since such a Matrix is ais a vector<Row>, any operation that can be applied to , any operation that can be applied to vector<Row> can be applied to a Matrix (including subscript)! can be applied to a Matrix (including subscript)!

Page 14: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

ExampleExample

With this definition (and a constructor we’ll With this definition (and a constructor we’ll write shortly), we can write: write shortly), we can write:

Matrix mat1(2,3);

inherited data member(s)

[0]

[1]

[0] [1] [2]mat1

cin >> mat1[0][0];

Page 15: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

ExampleExample

With this definition (and a constructor we’ll With this definition (and a constructor we’ll write shortly), we can write: write shortly), we can write:

Matrix mat1(2,3);

inherited data member(s)

[0]

[1]

[0] [1] [2]mat1

cin >> mat1[0][0];

The first subscript selects the The first subscript selects the Row whose index is 0 within whose index is 0 within mat1mat1..

Page 16: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

ExampleExample

With this definition (and a constructor we’ll With this definition (and a constructor we’ll write shortly), we can write: write shortly), we can write:

Matrix mat1(2,3);

inherited data member(s)

[0]

[1]

[0] [1] [2]mat1

cin >> mat1[0][0];

The first subscript selects the The first subscript selects the Row whose index is 0 within whose index is 0 within mat1mat1..

The second subscript selects the column whose index is 0 with in The second subscript selects the column whose index is 0 with in that that Row..

Page 17: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

InheritanceInheritanceIn such a declaration, Matrix is said to be In such a declaration, Matrix is said to be derived fromderived from vector<Row>. .

The Matrix class is said to The Matrix class is said to inheritinherit all of the members (data and function) of all of the members (data and function) of vector<Row>..

The pattern for such a declaration is as follows:The pattern for such a declaration is as follows:

class ChildClass : public ParentClass{ // ...};

ChildClassChildClass is derived from is derived from ParentClassParentClass, and inherits all of its , and inherits all of its members, both function and data.members, both function and data.

Page 18: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

Inheritance (Inheritance (Ct’dCt’d))

The The is-ais-a relationship is relationship is often drawn like this:often drawn like this:

Parent Class

Derived Class

A parent class can have many A parent class can have many derived classes, which are derived classes, which are sometimes called sometimes called child classeschild classes::

Parent Class

Child1 Child2 ChildN

. . .

Page 19: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

Inheritance (Inheritance (Ct’dCt’d))

Child classes can also be Child classes can also be parents, producing parents, producing class class hierarchieshierarchies::

Such hierarchies are Such hierarchies are useful for modeling useful for modeling relationships among relationships among real world objects. real world objects.

Parent Class

Child1 Child2 ChildN. . .

GChild1 GChild2 GChild3

Vehicle

Boat Car Truck. . .

compact wagon

. . .

. . .

sedan.

. .

. .

.

. .

.

By consolidating common By consolidating common code in parent classes, code in parent classes, inheritance can eliminate inheritance can eliminate all redundant code.all redundant code.

Page 20: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

Using InheritanceUsing InheritanceInheritance can be used to declare any class that is a special instance of another class. Inheritance can be used to declare any class that is a special instance of another class.

Since the derived class inherits all members of the parent class, inheritance should Since the derived class inherits all members of the parent class, inheritance should onlyonly be be used if every operation on the parent class can be appropriately applied to the derived classused if every operation on the parent class can be appropriately applied to the derived class

Page 21: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

Declaring MatrixDeclaring Matrix

We can thus start a Matrix class as follows:We can thus start a Matrix class as follows:typedef vector<double> Row;class Matrix : public vector<Row>{ public: private: int myRows, myColumns;};

No No myGridmyGrid data member is needed, because Matrix inherits the implementation details of data member is needed, because Matrix inherits the implementation details of vector<Row>.vector<Row>.

The data members The data members myRowsmyRows and and myColumnsmyColumns are not required, but they simplify some operations. are not required, but they simplify some operations.

Page 22: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

The Matrix InterfaceThe Matrix Interfaceclass Matrix : public vector<Row>{ public:

private: // ... data members omitted};

Matrix(); Matrix(int rows, int columns); int Rows() const; int Columns() const; Matrix operator+(const Matrix & mat2) const; // ... other Matrix-specific operations void Read(istream & in); void Print(ostream & out) const; friend istream & operator>>(istream & in,

Matrix & chart); friend ostream & operator<<(ostream & in,

const Matrix & chart);

Page 23: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

Default ConstructorDefault Constructor

The default constructor initializes the data The default constructor initializes the data members to default values:members to default values:Matrix mat1;

Specification:Specification:Postcondition: Postcondition: myRowsmyRows == 0 && == 0 && myColumnsmyColumns == 0. == 0.

We should use the vector<Row> constructor to We should use the vector<Row> constructor to initialize the inherited data members...initialize the inherited data members...

Page 24: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

Default ConstructorDefault Constructor

inline Matrix::Matrix() : vector<Row>(){ myRows = 0; myColumns = 0;}

This is sufficiently simple to define This is sufficiently simple to define inlineinline in Student.h: in Student.h:

Page 25: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

Default ConstructorDefault Constructor

inline Matrix::Matrix() : vector<Row>(){ myRows = 0; myColumns = 0;}

This is sufficiently simple to define This is sufficiently simple to define inlineinline in Student.h: in Student.h:

The notation The notation : vector<Row>() calls the constructor for class calls the constructor for class vector<Row> (Matrix’s (Matrix’s parent class).parent class).

A derived class constructor can (and should) always use this pattern to call the constructor A derived class constructor can (and should) always use this pattern to call the constructor of its parent class, to initialize its inherited data members.of its parent class, to initialize its inherited data members.

Page 26: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

Explicit-Value ConstructorExplicit-Value Constructor

Matrix mat1(3, 5);

This constructor lets you construct a Matrix This constructor lets you construct a Matrix of a specified size (in rows and columns):of a specified size (in rows and columns):

Specification:Specification:Receive: Receive: rowsrows, , columnscolumns, two int values., two int values.Precondition: Precondition: rowsrows > 0 && > 0 && columnscolumns > 0. > 0.Postcondition: Postcondition: myRowsmyRows == == rowsrows && && myColumnsmyColumns == == columnscolumns

&& I contain a 2-D vector of && I contain a 2-D vector of rowsrows rows and rows and columnscolumns columns. columns.

0 0 0 0 0

0 0 0 0 0

0 0 0 0 0

[0] [1] [2] [3] [4]

[2]

[1]

[0]

???mat1

myRowsmyColumns

3

5

The inherited data are The inherited data are wrapped in orange.wrapped in orange.

Page 27: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

Explicit-Value ConstructorExplicit-Value Constructor

inline Matrix:: Matrix(int rows, int columns) : vector<Row>(rows, Row(columns)){ assert(rows > 0 && columns > 0); myRows = rows; myColumns = columns;}

This is sufficiently simple to define inline:This is sufficiently simple to define inline:

Page 28: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

Explicit-Value ConstructorExplicit-Value Constructor

inline Matrix:: Matrix(int rows, int columns) : vector<Row>(rows, Row(columns)){ assert(rows > 0 && columns > 0); myRows = rows; myColumns = columns;}

This is sufficiently simple to define inline:This is sufficiently simple to define inline:

The The : vector<Row>(rows, Row(columns)) calls calls vector<Row>() to initialize the inherited to initialize the inherited members.members.

This constructor lets the caller specify the size (This constructor lets the caller specify the size (rows), and the initial value (), and the initial value (Row(columns)) of the vector.) of the vector.

The The Row constructor (i.e., constructor (i.e., vector<double>) is used to define the initial value as a vector of size ) is used to define the initial value as a vector of size columns..

Page 29: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

ExtractorsExtractors

The extractors retrieve data member The extractors retrieve data member values:values:

cout << mat1.Rows() << mat1.Columns();

Specifications:Specifications: Rows():Rows(): Return Return myRowsmyRows..

Columns():Columns():Return Return myColumnsmyColumns..

Page 30: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

ExtractorsExtractors

inline int Matrix::Rows() const{ return myRows;}

These are sufficiently simple to define These are sufficiently simple to define inlineinline::

inline int Matrix::Columns() const{ return myColumns;}

Page 31: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

Element AccessElement Access

Thanks to our having derived Matrix from Thanks to our having derived Matrix from vector<Row>, we can write:vector<Row>, we can write:

cout << mat1[r][c];

and access the element at row and access the element at row r, column , column c, , using the inherited subscript operators. using the inherited subscript operators.

Page 32: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

Element AccessElement Access

Thanks to our having derived Matrix from Thanks to our having derived Matrix from vector<Row>, we can write:vector<Row>, we can write:

cout << mat1[r][c];

and access the element at row r, column c, using the inherited subscript operators.and access the element at row r, column c, using the inherited subscript operators.

Since mat1 is a vector<Row>, sending mat1 the subscript message [r] accesses the Row in mat1 whose index is r.

Page 33: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

Element AccessElement Access

Thanks to our having derived Matrix from Thanks to our having derived Matrix from vector<Row>, we can write:vector<Row>, we can write:

cout << mat1[r][c];

and access the element at row r, column c, using the inherited subscript operators.and access the element at row r, column c, using the inherited subscript operators.

Since Since mat1 is a is a vector<Row>vector<Row>, sending , sending mat1 the subscript message the subscript message [r][r] accesses the accesses the RowRow in in mat1 whose index is whose index is rr..

We then send that Row the subscript message [c], which accesses the column within that Row whose index is c.

Page 34: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

Print()Print()

mat1.Print(cout);

This member lets you write a matrix to an This member lets you write a matrix to an ostream:ostream:

Specification:Specification:Receive: Receive: outout, an ostream., an ostream.Output: my (Matrix) values, to Output: my (Matrix) values, to outout..Passback: Passback: outout, containing my Matrix values;, containing my Matrix values;

Page 35: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

Defining Print()Defining Print()

// ...void Matrix::Print(ostream & out) const{ for (int r = 0; r < Rows(); r++) // for each r for (int c = 0; c < Columns(); c++) // for each c { fout << (*this)[r][c]; // display if (c < Columns()-1) // either out << ‘\t’; // tab else // or out << ‘\n’; // newline }}

This is sufficiently complicated to define separately.This is sufficiently complicated to define separately.

Page 36: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

thisthisThe tricky thing here is that within a function member, we must send The tricky thing here is that within a function member, we must send ourselvesourselves the subscript message. the subscript message.

Every C++ Every C++ function memberfunction member has a variable named has a variable named this..

When that member’s message is sent to an object, the address of the receiving object is stored in When that member’s message is sent to an object, the address of the receiving object is stored in this..

mat1.Print(cin);

Matrix::Print()

this

mat1

Page 37: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

this (this (Ct’dCt’d))In a C++ function member, In a C++ function member, this always contains the address of the object receiving the message. always contains the address of the object receiving the message.

Since it stores an address, Since it stores an address, this can be thought of as can be thought of as pointing topointing to the object receiving the message, and address-storing variables are commonly called the object receiving the message, and address-storing variables are commonly called pointerspointers. .

Since the value of Since the value of this is an is an addressaddress, we can’t use it as is to refer to the receiver of the message., we can’t use it as is to refer to the receiver of the message.

Page 38: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

this (this (Ct’dCt’d))When applied to a pointer as a prefix operator, the asterisk (When applied to a pointer as a prefix operator, the asterisk (*) produces as its value the object pointed to.) produces as its value the object pointed to.

That is, if we use the notation:That is, if we use the notation:

(*this)

within a function member, the effect will be to access the receiver of the message (i.e., ourselves).within a function member, the effect will be to access the receiver of the message (i.e., ourselves).

To send ourselves the subscript message, we thus write:To send ourselves the subscript message, we thus write:

(*this)[r][c]

which selects the which selects the Row whose index is whose index is r within ourselves (and then sends that within ourselves (and then sends that Row a second subscript message). a second subscript message).

Page 39: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

InsertionInsertion

cout << mat << endl;

Overloading the insertion operator will let us Overloading the insertion operator will let us display a Matrix in the “normal” manner:display a Matrix in the “normal” manner:

Since its left operand is an ostream, this function cannot Since its left operand is an ostream, this function cannot be implemented as a function member.be implemented as a function member.

Specification:Specification:Receive: Receive: outout, an ostream; , an ostream; matmat, a Matrix., a Matrix.Output: the values in Output: the values in matmat, via , via outout..Passback: Passback: outout, containing the Matrix., containing the Matrix.Return: Return: outout, for chaining., for chaining.

Page 40: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

Defining InsertionDefining Insertion

// ...inline ostream & operator<<(ostream & out, const Matrix & mat){ mat.Print(out); // send mat the Print() msg return out; // allow chaining}

Thanks to Print(), this is sufficiently simple to inline.Thanks to Print(), this is sufficiently simple to inline.

We simply send our Matrix parameter the Print() message, and let it do the work...We simply send our Matrix parameter the Print() message, and let it do the work...

Page 41: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

Read()Read()

mat1.Read(cin);

This member lets you read a matrix via an This member lets you read a matrix via an istream:istream:

Specification:Specification:Receive: Receive: inin, an istream., an istream.Precondition: Precondition: inin contains the values of an m-by-n matrix, contains the values of an m-by-n matrix,

with each row on a separate line.with each row on a separate line.Input: the matrix values, via Input: the matrix values, via inin..Passback: Passback: inin, the matrix values extracted from it., the matrix values extracted from it.Postcondition: I contain the input values.Postcondition: I contain the input values.

Page 42: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

Defining Read()Defining Read()

// ...void Matrix::Read(istream & in){ double number; char separator; for (;;) // row-loop { Row aRow; // empty row for (;;) // column-loop { in >> number; // read number if (in.eof()) break; // quit if failed aRow.push_back(number); // append number in.get(separator); // read next char if (separator == ‘\n’) break;// quit if e-o-l } // end column-loop if (in.eof()) break; // quit if eof push_back(aRow); // append Row } // end row-loop}

This is sufficiently complicated to define separately.This is sufficiently complicated to define separately.

Page 43: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

ExtractionExtraction

cin >> mat1;

The extraction operator lets us read a Matrix The extraction operator lets us read a Matrix from an istream, like any other object:from an istream, like any other object:

Specification:Specification:Receive: Receive: inin, an istream; , an istream; matmat, a Matrix., a Matrix.Precondition: Precondition: myRowsmyRows == == mm && && myColumnsmyColumns == == nn && &&

inin contains the values of an m-by-n matrix, contains the values of an m-by-n matrix, with one with one row/line.row/line.

Input: the matrix, via Input: the matrix, via inin..Passback: Passback: inin, the matrix read from it; , the matrix read from it;

matmat, containing the extracted values., containing the extracted values.Return: Return: inin, for chaining., for chaining.

Page 44: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

Defining ExtractionDefining Extraction

// ...inline istream & operator>>(istream & in, Matrix & mat){ mat.Read(in); return in;}

Thanks to Read(), this is simple enough to inline:Thanks to Read(), this is simple enough to inline:

We simply send our Matrix parameter the Read() message, and let it do the work...We simply send our Matrix parameter the Read() message, and let it do the work...

Page 45: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

Matrix AdditionMatrix Addition

Matrix mat3 = mat1 + mat2;

Defining the + operator will let us add Defining the + operator will let us add matrices:matrices:

Since its left operand is a Matrix, we Since its left operand is a Matrix, we cancan define operator+ as a Matrix define operator+ as a Matrix function member, in which case such an expression will be treated as:function member, in which case such an expression will be treated as:

Matrix mat3 = mat1.operator+(mat2);

Specification:Specification:Receive: Receive: mat2mat2, a Matrix., a Matrix.Precondition: Precondition: mat2.Rows() == myRows && mat2.Rows() == myRows && mat2.Columns() == mat2.Columns() ==

myColumnsmyColumns..Return: Return: mat3mat3, containing the sum of myself and , containing the sum of myself and mat2mat2..

Page 46: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

Addition OperatorAddition Operator

// ...Matrix Matrix::operator+(const Matrix & mat2) const{ assert(mat2.Rows() == myRows && mat2.Columns() == myColumns);

Matrix result(myRows, myColumns);

for (int r = 0; r < myRows; r++) for (int c = 0; c < myColumns; c++) result[r][c] = (*this)[r][c] + mat2[r][c];

return result;}

This is sufficiently complicated to define separately.This is sufficiently complicated to define separately.

Since the problem requires that we access all of the values in a 2-D structure, we use two Since the problem requires that we access all of the values in a 2-D structure, we use two nested for loops.nested for loops.

Page 47: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

Our ProgramOur Program

// ...int main(){ // ... cin >> mat1; // ... cin >> mat2; // ... Matrix mat3 = mat1 + mat2; // ... cout << mat3; // ...}

Our program will now work “as advertised”.Our program will now work “as advertised”.

All of our work is reuseable, and we can add more matrix-specific operations to class All of our work is reuseable, and we can add more matrix-specific operations to class Matrix...Matrix...

Page 48: Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.

SummarySummaryIf a new class is a special instance of an existing class, If a new class is a special instance of an existing class, derivationderivation can be used to define the can be used to define the

new class.new class.

A derived class A derived class inheritsinherits all members (except constructors and destructors) of its parent all members (except constructors and destructors) of its parent class.class.

A derived class constructor should use the parent class constructor to initialize inherited A derived class constructor should use the parent class constructor to initialize inherited data members.data members.

In function members, In function members, this is built-in variable containing the address of the receiver of the is built-in variable containing the address of the receiver of the message.message.

Within a function member, the expression Within a function member, the expression (*this) refers to the object receiving the refers to the object receiving the message.message.