How are objects passed to functions, and what is passed?
Feb 23, 2013 at 3:20pm UTC
Friendship and inheritance
http://www.cplusplus.com/doc/tutorial/inheritance/
Friend functions:
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 :
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;
}
1.) Between line 19 and 25, can we use this too?:
1 2 3 4 5 6
CRectangle duplicate (CRectangle rectparam)
{
rectparam.width*=2;
rectparam.height*=2;
return (rectparam);
}
2.) Why do not change the values of width and height of the rect object?
The rect was passed to duplicate() for duplicating rect's width and height, or not?
Here is the main() about what I think of:
1 2 3 4 5 6 7 8 9
int main () {
CRectangle rect, rectb;
rect.set_values (2,3);
rectb = duplicate (rect);
cout << rect.area(); // <--added this line
cout << '\n' ;
cout << rectb.area();
return 0;
}
6
24
I may have a tip:
The values of the variables of rect was copied to rectparam,
then only rectparam's variables was modified?
Feb 23, 2013 at 3:26pm UTC
Feb 23, 2013 at 3:46pm UTC
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
// 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&); // object passed by reference
};
void CRectangle::set_values (int a, int b) {
width = a;
height = b;
}
CRectangle duplicate (CRectangle& rectparam) // object passed by reference
{
rectparam.width*=2;
rectparam.height*=2;
return (rectparam);
}
int main () {
CRectangle rect, rectb;
rect.set_values (2,3);
rectb = duplicate (rect);
cout << rect.area(); // <--added this line
cout << '\n' ;
cout << rectb.area();
return 0;
}
24
24
Ok. Now I see. Thanks.
Topic archived. No new replies allowed.