Friendship and overloading

I've managed to break this program here but I'm not sure why it isn't working.

Could anybody point out to me what errors I have made.

Here is the broken 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
// friend functions
#include <iostream>
using namespace std;

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

CRectangle::CRectangle (int a, int b) {
  width = new int;
  height = new int;
  *width = a;
  *height = b;
}

CRectangle duplicate (CRectangle rectparam)
{
  CRectangle rectres;
  rectres.*width = rectparam.*width*2;
  rectres.*height = rectparam.*height*2;
  return (rectres);
}

int main () {
  CRectangle rect (2,3), rectb;
  rectb = duplicate (rect);
  cout << rectb.area();
  return 0;
}


Here is the functional 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 functions
#include <iostream>
using namespace std;

class CRectangle {
    int width, height;
  public:
    void set_values (int, int);
    int area () {return (width * height);}
    friend CRectangle duplicate (CRectangle);
};

void CRectangle::set_values (int a, int b) {
  width = a;
  height = b;
}

CRectangle duplicate (CRectangle rectparam)
{
  CRectangle rectres;
  rectres.width = rectparam.width*2;
  rectres.height = rectparam.height*2;
  return (rectres);
}

int main () {
  CRectangle rect, rectb;
  rect.set_values (2,3);
  rectb = duplicate (rect);
  cout << rectb.area();
  return 0;
}
You should provide a default constructor for class CRectangle (the one with no arguments), because the line CRectangle rect (2,3), rectb; calls for one. Ideally:
1
2
3
4
CRectangle::CRectangle () {
  width = new int; // ideally assign memory to this pointers now
  height = new int;
}
Last edited on
Where would I add in the default constructor at?

I thought declaring the constructer here was enough for that

1
2
3
4
5
6
CRectangle::CRectangle (int a, int b) {
  width = new int;
  height = new int;
  *width = a;
  *height = b;
}
Your constructor is enough if you wish to create rectangles like this:
CRectangle rect (a, b);
But if you wih to create them like you did with rectb:
CRectangle rectb; - you are in fact calling the nonexistant function CRectangle::CRectangle (); So your options are limited to either not creating rectangles without params, or providing another constructor to your class.

You add additional constructors like any other member functions, so first insert function prototype CRectangle::CRectangle (); into class body (make it public!), and then insert implementation (my code in previous post) somewhere outside the class, preferably next to your own constructor.
You can make as many different constructors as you want, as long as they take different parameters.
Last edited on
Topic archived. No new replies allowed.