#include<iostream>
using namespace std;
class my_class
{
int m,n;
public:
void show(void);
my_class& test(my_class b)
{
static my_class c;
c.m=m+b.m;
c.n=n+b.n;
return c;
}
my_class(int x,int y) //Parametrized constructor
{
m=x;n=y;
}
my_class(){} //Default consructor
};
void my_class::show(void)
{
cout<<m<<" "<<n;
}
main()
{
my_class a(2,3),b(3,4); //Object initialisation
my_class d=a.test(b);
d.show();
}
The function test
returns a reference to a static object c
defined in the function.I get the output as 5 7
.I need help regarding the following:
my_class
instead of my_class&
.How does return by value compare with return by reference here?Are data members of the returned reference copied in the assignment statement my_class d=a.test(b)
to object d
? Or is d
just an alias for the returned reference?If I change the assignment statement to my_class& d=a.test(b)
,
even then I get the same output.Does this mean that both ways of
writing the above statement are right?
Can you please explain what exactly is happening in both the kinds of assignment statements?
How does return by value compare with return by reference here?Are data members of the returned reference copied in the assignment statement my_class d=a.test(b) to object d?
Yes, d
is copy-initialized using the referenced object. (Although, that's indeed not an assignment, nor a statement).
...Or is d just an alias for the returned reference?
No, d
is not a reference, and not an alias of a reference. It is a non-reference variable.
If I changed the assignment statement to my_class& d=a.test(b), even then I get the same output?Does this mean that both ways of writing the above statement are right?
Depends on the definition of right. Neither of the options are ill-formed, but they do different things. What is right depends on what you intend to do.
Can you please explain what exactly is happening in both the kinds of assignment statements?
The standard allows some of the mentioned copies to be elided.