473,385 Members | 1,356 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

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()...instead i am getting garbage values when i print it...

here is my code :

Expand|Select|Wrap|Line Numbers
  1. #include <iostream.h>
  2. #include <stdio.h>
  3. #include <conio.h>
  4. #include <stdlib.h>
  5.  
  6. // general function declarations
  7.  
  8. void list (int *choice);
  9.  
  10.  
  11. // class declaration
  12. class matrix
  13. {
  14.     private :
  15.         int rows;
  16.         int columns;
  17.         int * element;
  18.  
  19.     public :
  20.         matrix();
  21.         matrix (int, int);
  22.         void setdata (int, int, int *);
  23.         void showptrdata();
  24.         matrix* operator+(matrix &);
  25.  
  26.     friend istream& operator >> (istream &, matrix &);
  27.     friend ostream& operator << (ostream &, matrix &);
  28.     // function overloading -- for printing a pointer object
  29.         friend ostream& operator << (ostream &, matrix *&);
  30.  
  31. };
  32.  
  33.  
  34. matrix :: matrix ()
  35. {
  36.     rows = 0;
  37.     columns = 0;
  38.     *element = 0;
  39. }
  40.  
  41. matrix :: matrix (int r ,int c)
  42. {
  43.     rows = r;
  44.     columns = c;
  45.     element = new int [rows * columns];
  46. }
  47.  
  48. istream& operator >> (istream &read, matrix &mat)
  49. {
  50.     for (int i = 0; i < mat.rows * mat.columns; ++i)
  51.         read >> *(mat.element+i);
  52.     return read;
  53. }
  54.  
  55. ostream& operator << (ostream &print, matrix &mat)
  56. {
  57.     for (int i = 0; i < mat.rows; ++i)
  58.     {
  59.         for (int j = 0; j < mat.columns; ++j)
  60.         {
  61.             print << *mat.element << "  ";
  62.             ++mat.element;
  63.         }
  64.         print << endl;
  65.     }
  66.     mat.element -= mat.rows * mat.columns;
  67.     return print;
  68. }
  69.  
  70. ostream& operator << (ostream &print, matrix *&mat)
  71. {
  72.  
  73.     for (int i = 0; i < mat->rows; ++i)
  74.     {
  75.         for (int j = 0; j < mat->columns; ++j)
  76.         {
  77.             print << *mat->element << "  ";
  78.             ++mat->element;
  79.         }
  80.         print << endl;
  81.     }
  82.     mat->element -= mat->rows * mat->columns;
  83.     return print;
  84. }
  85.  
  86. matrix*  matrix :: operator + (matrix &matrix2)
  87. {
  88.     matrix result (rows, columns);
  89.     for (int i=0; i< rows * columns; ++i)
  90.         *(result.element+i) = *(element+i) + *(matrix2.element+i);
  91.     //printf ("%d %d\n", result.rows, result.columns);
  92.     //printf ("%u %u %u \n", &result, &result.rows, &result.columns);
  93.     return &result;
  94. }
  95.  
  96. void main()
  97. {
  98.     clrscr();
  99.  
  100.     int r, c;
  101.     int choice;
  102.  
  103.     cout << "Enter the rows of the matrix : ";
  104.     cin >> r;
  105.     cout << "Enter the columns of the matrix : ";
  106.     cin >> c;
  107.  
  108.     matrix matrix1 (r, c);
  109.  
  110.     cout << "Enter the elements rowwise : " << endl;
  111.     cin >> matrix1;
  112.  
  113.  
  114.     cout << "You have created the following matrix : " << endl;
  115.     cout << matrix1;
  116.     cin.ignore();
  117.     cin.get();
  118.  
  119.     do
  120.     {
  121.  
  122.         list (&choice);
  123.  
  124.         switch (choice)
  125.         {
  126.             case 1 :
  127.                 cout << endl << endl << "The matrix is as follows : " << endl;
  128.                 cout << matrix1;
  129.             break;
  130.  
  131.             case 2 :
  132.                 cout << "Enter the new values of the matrix : " << endl;
  133.                 cin >> matrix1;
  134.                 cout << "The modified matrix is : " << endl;
  135.                 cout << matrix1;
  136.  
  137.             break;
  138.  
  139.             case 3 :
  140.                 matrix matrix2(r,c);
  141.                 cout << "Enter the elements of the second matrix : " << endl;
  142.                 cin >> matrix2;
  143.                 matrix *result;
  144.                 result = matrix1 + matrix2;
  145.                 //printf ("%u\n", result);
  146.                 //printf ("%u %u\n", &result->rows, &result->columns);
  147.                 //printf ("%d %d\n", result->rows, result->columns);
  148.                 cout << "The resultant matrix is : " << endl;
  149.                    cout << result;
  150.             break;
  151.  
  152.             case 4 :
  153.             break;
  154.  
  155.             case 5 :
  156.             break;
  157.  
  158.             case 6 :
  159.             break;
  160.  
  161.             case 0 :
  162.             exit(0);
  163.         }
  164.         cin.ignore();
  165.         cin.get();
  166.     } while (choice != 0);
  167.  
  168. }
  169.  
  170. void list (int *choice)
  171. {
  172.     clrscr();
  173.     cout << "1. Display the matrix." << endl << "2. Modify the matrix." << endl
  174.           << "3. Matrix Addition." << endl << "4. Matrix subtraction." << endl
  175.           << "5. Matrix multiplication." << endl
  176.           << "6. Transpose of matrix." << endl << "0.Exit." << endl;
  177.  
  178.     cin >> *choice;
  179.     cin.ignore();
  180.     if (!(*choice >= 0 && *choice <= 6))
  181.     {
  182.         cout << "Invalid choice." << endl;
  183.         cin.get();
  184.         list (choice);
  185.     }
  186. }

i have given the bold effect to the code that i felt is related to my problem..so..pls 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...still i would like to learn a way if any... :)
Mar 17 '08 #1
4 1803
JosAH
11,448 Expert 8TB
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
Mar 17 '08 #2
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...
Mar 17 '08 #3
JosAH
11,448 Expert 8TB
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
Mar 17 '08 #4
fual
28
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:
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2.  
  3. // general function declarations
  4. // class declaration
  5. class matrix
  6. {
  7.   private :
  8.     int rows;
  9.     int columns;
  10.     int * element;
  11.  
  12.   public :
  13.     matrix();
  14.     matrix (int, int);
  15.  
  16.     void set_data(int row, int column, int data){
  17.       *(element + (row * columns + column)) = data;
  18.     }
  19.  
  20.     matrix operator+=(const matrix &);
  21.  
  22.     friend std::istream& operator >> (std::istream &, matrix &);
  23.     friend std::ostream& operator << (std::ostream &, matrix &);
  24. };
  25.  
  26.  
  27. matrix::matrix() : rows(0), columns(0), element(0) {}
  28.  
  29. matrix :: matrix (int r ,int c) : rows(r), columns(c), element( new int [rows * columns] ){ }
  30.  
  31. std::istream& operator >> (std::istream &read, matrix &mat)
  32. {
  33.   for (int i = 0; i < mat.rows * mat.columns; ++i)
  34.     read >> *(mat.element+i);
  35.   return read;
  36. }
  37.  
  38. std::ostream& operator << (std::ostream &print, matrix &mat)
  39. {
  40.   for (int i = 0; i < mat.rows; ++i)
  41.   {
  42.     for (int j = 0; j < mat.columns; ++j)
  43.     {
  44.       print << *mat.element << "  ";
  45.       ++mat.element;
  46.     }
  47.     print << std::endl;
  48.   }
  49.   mat.element -= mat.rows * mat.columns;
  50.   return print;
  51. }
  52.  
  53.  
  54. matrix  matrix :: operator+= (const matrix& that)
  55. {
  56.  
  57.   for (int i=0; i != rows * columns; ++i)
  58.     *(element+i) += *(that.element+i);
  59.   return matrix( *this );
  60. }
  61.  
  62. int main()
  63. {
  64.   matrix m(2,2), n(2,2);
  65.   m.set_data(0,0,1);
  66.   m.set_data(1,0,2);
  67.   m.set_data(0,1,3);
  68.   m.set_data(1,1,4);
  69.  
  70.   n += m;
  71.   n += m;
  72.  
  73.   std::cout << m;
  74.   std::cout << n;
  75.  
  76.   matrix p(n);
  77.   std::cout << p;
  78.  
  79.   p.set_data(0,0,0);
  80.   std::cout << n;
  81.  
  82.   return 0;
  83. }
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.
Mar 17 '08 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

9
by: mjm | last post by:
Folks, Stroustrup indicates that returning by value can be faster than returning by reference but gives no details as to the size of the returned object up to which this holds. My question is...
5
by: Gent | last post by:
I have two questions which are very similar: Is it possible to return an object in C++. Below is part of my code for reference however I am more concerned about the concept. It seems like the...
3
by: Alfonso Morra | last post by:
I'm in the process of implementing an abstract factory design pattern for an application. I would like to know, which is the recommended way of returning objects from the factory - by reference or...
1
by: Protoman | last post by:
When would you return a const reference/pointer from a function instead of either the object itself, or a non constreference/pointer? And when would you need to return a reference or pointer at...
4
by: Dan | last post by:
I have class B and C which inherit from class A. I have a static method: A* aRequest(unsigned char *byte_buffer, size_t length) { A *foo; if(something == true) { foo = new B;
17
by: I.M. !Knuth | last post by:
Hi. I'm more-or-less a C newbie. I thought I had pointers under control until I started goofing around with this: ...
6
by: student1976 | last post by:
All Beginner/Intermediate level question. I understand that returning ptr to local stack vars is bad. Is returning foo_p_B from fnB() reliable all the time, so that using foo_p_A does not...
23
by: pauldepstein | last post by:
Below is posted from a link for Stanford students in computer science. QUOTE BEGINS HERE Because of the risk of misuse, some experts recommend never returning a reference from a function or...
8
by: darren | last post by:
Hi everybody, have a quick look at this code: ===== ===== int main(void) { string msg; makeString(msg); cout << "back in main, result = " << msg << endl;
5
by: ctj951 | last post by:
I have a very specific question about a language issue that I was hoping to get an answer to. If you allocate a structure that contains an array as a local variable inside a function and return...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.