'C++ Matrix class for beginners

Please check the code below that why this code did not display output??? The program works fine when calling a constructor but when I call the function to display record, it did not display it. I want to complete this work without overloading of = and << operators.

#include <iostream>
#include <string.h>
using namespace std;

class Matrix{
    private:
        int noOfRows;
        int noOfColumns;
        int **data;
    public:
        Matrix(int noOfRows, int noOfColumns);
        void displayData();
        ~Matrix();
        Matrix (const Matrix &ref);
};

Matrix::Matrix(int noOfRows=0, int noOfColumns=0){
    data=new int*[noOfColumns];
    for(int i=0;i<noOfRows;i++)
        data[i]=new int[noOfColumns];
    int d;
    for(int r=0;r<noOfRows;r++){
        for(int c=0;c<noOfColumns;c++){
            cout<<"Enter ...";cin>>d;
            data[r][c]=d;
        //  cout<<data[r][c]<<"\t"; 
        }
        cout<<endl;
    }
    for(int r=0;r<noOfRows;r++){
        for(int c=0;c<noOfColumns;c++)
            cout<<data[r][c]<<"\t";
        cout<<endl;
    }
}

Matrix::Matrix (const Matrix &ref){
    this->data=new int*[ref.noOfColumns];
    for(int i=0;i<ref.noOfRows;i++)
        this->data[i]=new int[ref.noOfColumns];
    
    for(int r=0;r<ref.noOfRows;r++){
        for(int c=0;c<ref.noOfColumns;c++){
            this->data[r][c]=ref.data[r][c];
            cout<<this->data[r][c]<<"\t";
        }
        cout<<endl;
    }
}

void Matrix::displayData(){
    for(int r=0;r<noOfRows;r++){
        for(int c=0;c<noOfColumns;c++)
            cout<<data[r][c]<<"\t";
        cout<<endl;
    }
}

Matrix::~Matrix(){
//  delete[] data;
}

main(){
    Matrix M(2,2);
    M.displayData();
}


Solution 1:[1]

You didn't initialize the data members noOfRows and noOfColumns in the constructor, and you confused matters by giving the constructor parameters the same names.

The constructor defintion should begin with:

Matrix::Matrix(int inr=0, int inc=0): noOfRows(inr), noOfColumns(inc)

(I would use unsigned int instead of int, but whatever floats your boat.)

Also, notice that if you actually create a matrix with zero rows or columns, the program won't output anything. Maybe displayData should print something "empty matrix" if NoOfRows or noOfColums is 0.

And more fun, data=new int*[0]; is legal, but unusable. Either check for a size 0 and consequently do nothing, or throw an exception.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1