why is my code doesn't work?

This code i take it from the tutorial here and when i make a few changes it gives me a wrong output

the original code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// friend class
#include <iostream>
using namespace std; 
class CSquare; 
class CRectangle { 
    int width, height; 
  public: 
    int area () 
      {return (width * height);} 
    void convert (CSquare a); 
}; 
class CSquare { 
  private: 
    int side; 
  public: 
    void set_side (int a) 
      {side=a;} 
    friend class CRectangle; 
}; 
void CRectangle::convert (CSquare a) { 
  width = a.side; 
  height = a.side; 
} 
   
int main () { 
  CSquare sqr; 
  CRectangle rect; 
  sqr.set_side(4); 
  rect.convert(sqr); 
  cout << rect.area(); 
  return 0; 
} 


the output of this code is 16

my code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// friend class
#include <iostream>
using namespace std;

class CRectangle {

  public:
      int width, height;
    int area ()
      {return (width * height);}
    friend class CSquare;

};

class CSquare {
  public:
      int side;
    void set_side (int a)
      {
          side=a;
    }
    void convert (CRectangle b);
};

void CSquare::convert (CRectangle b) {
  b.width = side;
  b.height = side;
}

int main () {
    CRectangle rect;
    CSquare sqr;
    sqr.set_side(4);
    sqr.convert(rect);
    cout << rect.area();
    return 0;
}


the output of this code is 2139508736

why my code doesn't work correctly?
thanks
You are ignoring a warning, that is rect is not initialized.But also initialising it will not help.

pass by reference in convert function will remove all possible errors.
You are ignoring a warning, that is rect is not initialized.But also initialising it will not help.


no there is no such warning (the program runs whithout warnings or errors)

pass by reference in convert function will remove all possible errors.


thanks alot , this worked

but why is that happen why in the first code it works correctly and in the second it doesn't. and why passing by reference works i would like to know more about why im getting this problem than how to solve it :)
rect is passed by value to convert which means it will be copied, so b in convert is a copy of rect in main. Changes made to the copy will not affect the original object so rect stays unchanged. If you pass it by reference instead, changes made to b will affect the object passed to the function which is probably what you want.
Peter87: Thanks
Topic archived. No new replies allowed.