Recap - Matrix Class
Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 47 of 104.
Challenge
EasyLet's build a Matrix class that brings together all the operator overloading techniques you've learned in this chapter. You'll create a fully-featured matrix that supports arithmetic operations, comparisons, element access, and stream output — all through intuitive operator syntax.
You'll organize your code across two files:
Matrix.h: Define aMatrixclass that manages a 2D array of integers using dynamic memory. Your matrix should support:- Private members: a
int**pointer for the 2D data, andsize_tmembers for rows and columns - A constructor that takes rows and columns, initializing all elements to 0
- A destructor that properly frees all allocated memory
- A copy constructor and copy assignment operator (deep copy with self-assignment check)
- Getters
getRows()andgetCols()(both const) - A
set(row, col, value)method to set individual elements - A
get(row, col)const method to retrieve elements
Implement these operators:
- Arithmetic:
+and-for matrix addition and subtraction (return new Matrix by value) - Comparison:
==and!=to check if two matrices have the same dimensions and identical elements - Stream:
<<as a friend function to output the matrix row by row, with elements separated by spaces and each row on a new line - Subscript:
[]that returns a pointer to a row, allowingmatrix[row][col]syntax (provide both const and non-const versions)
For arithmetic operators, assume both matrices have the same dimensions. Comparison operators should return
falseif dimensions differ.- Private members: a
main.cpp: Read input to create and manipulate two 2x2 matrices. The input format is:- Four integers for the first matrix (row by row): a00, a01, a10, a11
- Four integers for the second matrix (row by row): b00, b01, b10, b11
Create two
Matrixobjects (2 rows, 2 columns each), populate them using theset()method, then demonstrate your operators:Output format:
Matrix A: <row0> <row1> Matrix B: <row0> <row1> A + B: <row0> <row1> A - B: <row0> <row1> A == B: <true/false> A != B: <true/false> A[0][0]: <value> A[1][1]: <value>Each row should display elements separated by single spaces. Print
trueorfalse(lowercase) for comparison results.
For example, with inputs 1 2 3 4 for Matrix A and 5 6 7 8 for Matrix B:
Matrix A:
1 2
3 4
Matrix B:
5 6
7 8
A + B:
6 8
10 12
A - B:
-4 -4
-4 -4
A == B: false
A != B: true
A[0][0]: 1
A[1][1]: 4Use std::stoi() for input conversion. Remember to implement != in terms of == to keep your operators consistent. Don't forget header guards in your header file.
Try it yourself
#include <iostream>
#include <string>
#include "Matrix.h"
using namespace std;
int main() {
// Read input for first matrix (2x2): a00, a01, a10, a11
int a00, a01, a10, a11;
cin >> a00 >> a01 >> a10 >> a11;
// Read input for second matrix (2x2): b00, b01, b10, b11
int b00, b01, b10, b11;
cin >> b00 >> b01 >> b10 >> b11;
// TODO: Create two Matrix objects (2 rows, 2 columns each)
// TODO: Populate matrices using the set() method
// TODO: Output Matrix A
// cout << "Matrix A:" << endl;
// Use the << operator to print the matrix
// TODO: Output Matrix B
// cout << "Matrix B:" << endl;
// Use the << operator to print the matrix
// TODO: Output A + B
// cout << "A + B:" << endl;
// TODO: Output A - B
// cout << "A - B:" << endl;
// TODO: Output comparison results
// cout << "A == B: " << (use ternary for true/false) << endl;
// cout << "A != B: " << (use ternary for true/false) << endl;
// TODO: Output subscript access results
// cout << "A[0][0]: " << ... << endl;
// cout << "A[1][1]: " << ... << endl;
return 0;
}
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesC++ Build & CompilationHeader Files & Source FilesNamespaces & ScopeIntroduction to OOP in C++Classes vs ObjectsThe 'this' PointerMethods (Member Functions)Attributes (Data Members)Ctors & Dtors BasicsRecap - Simple Calculator4Class Properties
Instance vs Static MembersGetters and SettersConst Member FunctionsMutable KeywordStatic Methods and VariablesFriend Functions & ClassesRecap - Bank Account Manager7Inheritance
Basic InheritanceInheritance Access LevelsCtor & Dtor Call OrderMethod OverridingVirtual Functions & VTableMultiple InheritanceVirtual InheritanceRecap - Employee Hierarchy2Memory Management
Stack vs Heap MemoryPointers and ReferencesDynamic Memory (new/delete)Smart Pointers in C++RAII in C++Recap - Dynamic Array Manager5Encapsulation
Access Specifiers in C++Access Specifiers In DepthInformation HidingStruct vs ClassNested & Inner ClassesRecap - Student Records System8Polymorphism
Compile vs Runtime PolymorphFunction OverloadingVirtual Functions RevisitedPure Virtual FunctionsAbstract ClassesInterface Design in C++Dynamic Casting & RTTIRecap - Shape Calculator3Constructors & Destructors
Default ConstructorParameterized ConstructorCopy ConstructorMove ConstructorConstructor Init ListsDelegating ConstructorsDestructor Deep DiveRule of Three / Five / ZeroRecap - String Class6Operator Overloading
Intro to Operator OverloadArithmetic Operator OverloadComparison Operator OverloadStream OperatorsAssignment Operator Overload[] and () Operator OverloadType Conversion OperatorsRecap - Matrix Class9Templates
Function TemplatesClass TemplatesTemplate SpecializationVariadic TemplatesSFINAE & Type Traits BasicsRecap - Generic Container