class date
{
int x,y,z;
public:
date(int a,int b, int c): x{a},y{b},z{c} {};
void show()
{
cout<<x<<endl<<y<<endl<<z;
}
};
const date& default_date()
{
staticconst date dd(1970,1,2);
return dd;
}
int main()
{
date t=default_date();
t.show();
return 0;
}
Put the code you need help with here.
here if we instead use - const date default_date(); it gives same result that i understand, but how using reference const date& default_date() eliminates unnecessary copying if default_date() is called many times during the program. .
Since you're assigning the return value of default_date() to an object, it makes absolutely no difference whether you return a reference or not, because assignment requires a copy.
If you did something like
1 2 3 4
for (int i = 0; i < 1000000; i++)
//Note: You would need to make date::show() a const function to
//be able to call it on this reference.
default_date().show();
not copy would happen at all. You would just be calling show() on the static instance in default_date().