Ans:. it avoids copying . But never return reference of local object .
So that functions can be l-values
We do this when we want to modify lvalue . we do this in operator overlaoding of " =" to support a=b=c chaining
MyClass & operator=(const MyClass &rhs);
MyClass & operator+=(const MyClass &rhs)
b) Returning just const
As const return can be assigned to nonconst variable and changed .
But if function is used in expression then temporary return as it is const will be prohibited .
struct foo
{
void bar() {}
void barfoo() const {}
};
foo foobar1() {return foo();}
const foo foobar2() {return foo();}
int main()
{
foobar1().barfoo(); //perfectly legal, calling const member function of non-const object
foobar1().bar(); //perfectly legal, calling non-const member function of non-const object
foobar2().barfoo(); // perfectly legal, calling const member function of const object
foobar2().bar(); // this willl not compile
}
In operator overloading we use it often to make sure
const MyClass MyClass::operator+(const MyClass &other) const
(a+b)=c // this kind of things will not get compile
We make sure (a+b).func() is allowed only if func()is const function .
this is called const correectness
c)When to return const refrence
This make lot of sense .
http://www.cs.caltech.edu/courses/cs11/material/cpp/donnie/cpp-ops.html
Nice post. Thanks for sharing the post
ReplyDeletedbms interview questions
spring interview questions
jsp interview questions
c++ interview questions
This comment has been removed by the author.
ReplyDeleteThanks for provide great informatic and looking beautiful blog
ReplyDeletepython training in bangalore | python online Training
artificial intelligence training in bangalore | artificial intelligence online training
machine learning training in bangalore | machine learning online training
uipath-training-in-bangalore | uipath online training
blockchain training in bangalore | blockchain online training
aws training in Bangalore | aws online training
data science training in bangalore | data science online training
hadoop training in bangalore | hadoop online training
iot training in bangalore | iot online training