home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #30 / NN_1992_30.iso / spool / comp / lang / cplus / 18103 < prev    next >
Encoding:
Text File  |  1992-12-16  |  1.4 KB  |  68 lines

  1. Path: sparky!uunet!spool.mu.edu!agate!apple!kaleida.com!moon!gordie
  2. From: gordie@duts.ccc.amdahl.com (Gordie Freedman)
  3. Newsgroups: comp.lang.c++
  4. Subject: Do temps hurt performance of overloaded +
  5. Date: 16 Dec 1992 23:57:58 GMT
  6. Organization: Happy hacker bait and tackle shop
  7. Lines: 55
  8. Distribution: world
  9. Message-ID: <1gofq7INN8q@golden.kaleida.com>
  10. Reply-To: gordie@duts.ccc.amdahl.com
  11. NNTP-Posting-Host: moon.kaleida.com
  12.  
  13. If I do the following to overload binary + for a class, will temporary
  14. objects be created? And if so, what can I do to prevent this, to get the best
  15. performance?
  16.  
  17.  
  18.  
  19. #include <stdio.h>
  20.  
  21. // Class definition
  22. class Complex
  23. {
  24. public:
  25.     Complex (void) : real(0.0), imaginary(0.0) {}
  26.     Complex (Complex& c) : real(c.real), imaginary(c.imaginary) {}
  27.     Complex (float x, float y) : real(x), imaginary(y) {}
  28.     friend Complex operator + (Complex& x, Complex& y);
  29.     void print (void);
  30.     
  31. private:
  32.     float real;
  33.     float imaginary;
  34. };
  35.  
  36. // Print routine
  37. void Complex::print (void)
  38. {
  39.     fprintf (stdout, "Real %g, imaginary %g\n", real, imaginary);
  40. }
  41.  
  42. // Overloaded + operator
  43. inline Complex operator + (Complex& x, Complex& y)
  44. {
  45.     return Complex (x.real + y.real, x.imaginary + y.imaginary);
  46.  
  47. // Main test routine
  48. int
  49. main (int argc, char** argv)
  50. {
  51.     Complex a(1, 2), b(10,20), c;
  52.     Complex* dp;
  53.  
  54.     c = a + b;
  55.     dp = new Complex (c + b);
  56.  
  57.     c.print();
  58.     dp->print();
  59.     return 0;    
  60. }    
  61.  
  62.     
  63. ---
  64. Gordie Freedman: gordie@kaleida.com Sigs are for kids
  65.  
  66.  
  67.