can we use cin>> in member functions in a class in C++?

Viewed 209

I'm trying to initialize a class matrix using a member function like thiis

class mat{
    int r,c;
    float **p;
    
    public:
    
    mat(){}
    mat(int,int);
    void initialize();
};
mat :: mat (int r, int c){ //check for float and int if error occurs
    p=new float*[r];
    for(int i=0; i<r; ++i){
        p[i]=new float(c);
    }
void mat :: initialize(void){
    int i,j;
    cout<<"\nEnter the elements : ";
    for(i=0;i<r;++i){
        for(j=0;j<c;++j){
            cin>>p[i][j];
        }
    }
}
int main(){
    mat m1(3,3);
    cout<<"\nInitialize M1";
    m1.initialize();
    
    
    return(0);
}

but when i compile and run it and try to initialize a matrix, program never stops to recieve inputs. Can anyone tell me what i'm doing wrong?

1 Answers

You need to initialize r and c like this:

mat :: mat (int r, int c) :r(r), c(c){
    p=new float*[r];
    for(int i=0; i<r; ++i){
        p[i]=new float[c];
    }
}

and don't forget to add the destructor.

Related