473,734 Members | 2,567 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

returning an object by pointer

8 New Member
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 :

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..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... :)
Mar 17 '08 #1
4 1820
JosAH
11,448 Recognized Expert MVP
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
Encrypted
8 New Member
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 Recognized Expert MVP
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 New Member
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
11916
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 up to which size m would you expect vector<double> returns_by_value() {
5
3100
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 function below is returning a pointer to pointers who are GUID. I am trying to write a wrapper to use in my VB code and what I would prefer to do is be able to return an array of GUID. I remember (not sure) that the concept of arrays does not really...
3
4319
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 by pointer? Returning pointers is a no brainer, but I'm not sure how to return a reference to a newly created object, in a method call. (Yes, I know about RAII). Pseudocode:
1
1247
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 all, instead of the object itself?
4
1402
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
3259
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: ================================================================================ /* A function that returns a pointer-of-arrays to the calling function. */ #include <stdio.h> int *pfunc(void);
6
1786
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 break? Thanks Josh
23
2937
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 method. QUOTE ENDS HERE I have never heard anyone else say that it is a problem for a function
8
2219
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
2680
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 that structure, is this valid? As shown in the code below I am allocating the structure in the function and then returning the structure. I know if the structure contained only simple types (int, float) this will work without problems as you...
0
8946
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8776
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9236
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9182
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6735
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6031
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3261
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2724
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.