C ++ object reference not set on an instance of an object

advertisements

When I try to compile the following program it says "Build failed. Object reference not set to an instance of an object" . I'm kinda new to c++ so if anybody can help me it'll be great . I'm just trying out some example I saw in a book so I don't know whats wrong with this .

using namespace std;

class matrix
{
    int m[3][3];

    public:
        void read(void);
        void display(void);

        friend matrix trans(matrix);
}

void matrix :: read(void)
{
    cout<<"Enter the elements of the 3x3 array matrix : \n";
    int i,j;
    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
        {
            cout<<"m["<<i<<"]["<<j<<"] =";
            cin>>m[i][j];
        }
    }
}

void matrix :: display(void)
{
    int i,j;
    for(i=0;i<3;i++)
    {
        cout<<"\n";
        for(j=0;j<3;j++)
        {
            cout<<m[i][j]<<"\t";
        }
    }
}

matrix trans(matrix m1)
{
    matrix m2;
    int i,j;
    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
        {
            m2.m[i][j] = m1.m[j][i];
        }
    }
    return(m2);             //returning an object
}

int main()
{
    matrix mat1,mat2;
    mat1.read();
    cout<<"\nYou entered the following matrix :";
    mat1.display();

    mat2 = trans(mat1);
    cout<<"\nTransposed matrix :";
    mat2.display();

    getch();
    return 0;
}


1 - Insert semi-colon after the class definition
2 - Insert the correct headers

   #include <iostream>
   #include <conio.h>

3 - Try getting a compiler that is a bit more descriptive with regards to errors. I did all that i mentioned and your program ran. Try it