returning an object by pointer

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Encrypted
    New Member
    • Mar 2008
    • 8

    returning an object by pointer

    i hav coded a matrix class and its member functions (many of them are overloaded ones)...now in a function..for eg. function of matrix addition.. after the addition i want to return the local object "result" through a pointer (and not call by value)..however i aint getting d values of the result in main()...instea d i am getting garbage values when i print it...

    here is my code :

    Code:
    #include <iostream.h>
    #include <stdio.h>
    #include <conio.h>
    #include <stdlib.h>
    
    // general function declarations
    
    void list (int *choice);
    
    
    // class declaration
    [B]class matrix
    {
    	private :
    		int rows;
    		int columns;
    		int * element;
    
    	public :
    		matrix();
    		matrix (int, int);
    		void setdata (int, int, int *);
    		void showptrdata();
    		matrix* operator+(matrix &);
    
    	friend istream& operator >> (istream &, matrix &);
    	friend ostream& operator << (ostream &, matrix &);
    	// function overloading -- for printing a pointer object
            friend ostream& operator << (ostream &, matrix *&);
    
    };[/B]
    
    
    matrix :: matrix ()
    {
    	rows = 0;
    	columns = 0;
    	*element = 0;
    }
    
    matrix :: matrix (int r ,int c)
    {
    	rows = r;
    	columns = c;
    	element = new int [rows * columns];
    }
    
    istream& operator >> (istream &read, matrix &mat)
    {
    	for (int i = 0; i < mat.rows * mat.columns; ++i)
    		read >> *(mat.element+i);
    	return read;
    }
    
    [B]ostream& operator << (ostream &print, matrix &mat)
    {
    	for (int i = 0; i < mat.rows; ++i)
    	{
    		for (int j = 0; j < mat.columns; ++j)
    		{
    			print << *mat.element << "  ";
    			++mat.element;
    		}
    		print << endl;
    	}
    	mat.element -= mat.rows * mat.columns;
    	return print;
    }
    
    ostream& operator << (ostream &print, matrix *&mat)
    {
    
    	for (int i = 0; i < mat->rows; ++i)
    	{
    		for (int j = 0; j < mat->columns; ++j)
    		{
    			print << *mat->element << "  ";
    			++mat->element;
    		}
    		print << endl;
    	}
    	mat->element -= mat->rows * mat->columns;
    	return print;
    }
    [/B]
    
    [B]matrix*  matrix :: operator + (matrix &matrix2)
    {
    	matrix result (rows, columns);
    	for (int i=0; i< rows * columns; ++i)
    		*(result.element+i) = *(element+i) + *(matrix2.element+i);
    	//printf ("%d %d\n", result.rows, result.columns);
    	//printf ("%u %u %u \n", &result, &result.rows, &result.columns);
    	return &result;
    }
    
    [/B]
    void main()
    {
    	clrscr();
    
    	int r, c;
    	int choice;
    
    	cout << "Enter the rows of the matrix : ";
    	cin >> r;
    	cout << "Enter the columns of the matrix : ";
    	cin >> c;
    
    	matrix matrix1 (r, c);
    
    	cout << "Enter the elements rowwise : " << endl;
    	cin >> matrix1;
    
    
    	cout << "You have created the following matrix : " << endl;
    	cout << matrix1;
    	cin.ignore();
    	cin.get();
    
    	do
    	{
    
    		list (&choice);
    
    		switch (choice)
    		{
    			case 1 :
    				cout << endl << endl << "The matrix is as follows : " << endl;
    				cout << matrix1;
    			break;
    
    			case 2 :
    				cout << "Enter the new values of the matrix : " << endl;
    				cin >> matrix1;
    				cout << "The modified matrix is : " << endl;
    				cout << matrix1;
    
    			break;
    
    			case 3 :
    [B]				matrix matrix2(r,c);
    				cout << "Enter the elements of the second matrix : " << endl;
    				cin >> matrix2;
    				matrix *result;
    				result = matrix1 + matrix2;
    				//printf ("%u\n", result);
    				//printf ("%u %u\n", &result->rows, &result->columns);
    				//printf ("%d %d\n", result->rows, result->columns);
    				cout << "The resultant matrix is : " << endl;
    			       cout << result;[/B]
    			break;
    
    			case 4 :
    			break;
    
    			case 5 :
    			break;
    
    			case 6 :
    			break;
    
    			case 0 :
    			exit(0);
    		}
    		cin.ignore();
    		cin.get();
    	} while (choice != 0);
    
    }
    
    void list (int *choice)
    {
    	clrscr();
    	cout << "1. Display the matrix." << endl << "2. Modify the matrix." << endl
    		  << "3. Matrix Addition." << endl << "4. Matrix subtraction." << endl
    		  << "5. Matrix multiplication." << endl
    		  << "6. Transpose of matrix." << endl << "0.Exit." << endl;
    
    	cin >> *choice;
    	cin.ignore();
    	if (!(*choice >= 0 && *choice <= 6))
    	{
    		cout << "Invalid choice." << endl;
    		cin.get();
    		list (choice);
    	}
    }

    i have given the bold effect to the code that i felt is related to my problem..so..pl s help me with this problem..
    and yes..one more question..is there any way to return this "result" by a reference ??? i know it may seem absurd...bcoz of the scope of the local variable...stil l i would like to learn a way if any... :)
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    You're returning the address (a pointer to) a local variable. When the function
    terminates the memory taken by the local variable (which was stored on the
    stack) is lost for the posterity. Don't use locals there, 'new' your new matrix.

    kind regards,

    Jos

    Comment

    • Encrypted
      New Member
      • Mar 2008
      • 8

      #3
      well...if u watch the code carefully...i have used new to allocate memory for that particular variable "result"... i have done that in the copy constructor which i have used while declaring "result" :

      matrix result (rows, columns);

      still i am facing the problem...
      however i think that even allocating might not be helping "result" because after all..its scope is local to the function..hence it might be getting destroyed..
      nevertheless any new suggestions are welcome...

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by Encrypted
        well...if u watch the code carefully...i have used new to allocate memory for that particular variable "result"... i have done that in the copy constructor which i have used while declaring "result" :

        matrix result (rows, columns);

        still i am facing the problem...
        however i think that even allocating might not be helping "result" because after all..its scope is local to the function..hence it might be getting destroyed..
        nevertheless any new suggestions are welcome...
        I did watch your code carefully and all you allocate is memory for the data
        elements; the rest of the matrix data (the variables rows and columns and the
        pointer to the elements) is still lost after the function terminates.

        There's no need for new suggestions, first you have to fix this bug.

        kind regards,

        Jos

        Comment

        • fual
          New Member
          • Feb 2008
          • 28

          #5
          You've got the right idea, but your code doesn't even come close to compiling. Start simple and go from there. A good approach is to get one aspect of your code working and then move on to the next thing, don't do it all at once. This should get you started:
          [CODE=cpp]#include <iostream>

          // general function declarations
          // class declaration
          class matrix
          {
          private :
          int rows;
          int columns;
          int * element;

          public :
          matrix();
          matrix (int, int);

          void set_data(int row, int column, int data){
          *(element + (row * columns + column)) = data;
          }

          matrix operator+=(cons t matrix &);

          friend std::istream& operator >> (std::istream &, matrix &);
          friend std::ostream& operator << (std::ostream &, matrix &);
          };


          matrix::matrix( ) : rows(0), columns(0), element(0) {}

          matrix :: matrix (int r ,int c) : rows(r), columns(c), element( new int [rows * columns] ){ }

          std::istream& operator >> (std::istream &read, matrix &mat)
          {
          for (int i = 0; i < mat.rows * mat.columns; ++i)
          read >> *(mat.element+i );
          return read;
          }

          std::ostream& operator << (std::ostream &print, matrix &mat)
          {
          for (int i = 0; i < mat.rows; ++i)
          {
          for (int j = 0; j < mat.columns; ++j)
          {
          print << *mat.element << " ";
          ++mat.element;
          }
          print << std::endl;
          }
          mat.element -= mat.rows * mat.columns;
          return print;
          }


          matrix matrix :: operator+= (const matrix& that)
          {

          for (int i=0; i != rows * columns; ++i)
          *(element+i) += *(that.element+ i);
          return matrix( *this );
          }

          int main()
          {
          matrix m(2,2), n(2,2);
          m.set_data(0,0, 1);
          m.set_data(1,0, 2);
          m.set_data(0,1, 3);
          m.set_data(1,1, 4);

          n += m;
          n += m;

          std::cout << m;
          std::cout << n;

          matrix p(n);
          std::cout << p;

          p.set_data(0,0, 0);
          std::cout << n;

          return 0;
          }[/CODE]

          You need to deal with copy construction and assignment (oh and destruction to clean up that pointer), because at the moment the pointer is copied, not the underlying data.

          Hope that helps.

          Comment

          Working...