S
Sree
Hello All,
When will it be benefical to return a value from a function as a const reference
?
Say I have classes like this
class B {
public:
int someValue1;
int someValue2;
void ChangeValue();
void ConstFunc() const;
};
void B::ChangeValue()
{
int tmp = someValue1;
someValue1 = someValue2;
someValue2 = tmp;
}
class A {
public :
int value;
void inspect(const B& b);
const B& returnConstRef();
private :
int someInt;
B classB;
};
const B& A::returnConstRef()
{
return classB;
}
In the above class, returnConstRef returns a const reference to B. So whatever
we get like this should not be able to change class B like below. Also the
compiler should not allow me to assign a non-const class B (classB) to classA.
returnConstRef().
A classA;
B classB = classA.returnConstRef();
classB.ChangeValue();
With the above code there is no problem with the compiler. I am wrong some where
in my understanding of the returning values by reference, Can somebody please
correct ?
Thanks in advance
KInd.
When will it be benefical to return a value from a function as a const reference
?
Say I have classes like this
class B {
public:
int someValue1;
int someValue2;
void ChangeValue();
void ConstFunc() const;
};
void B::ChangeValue()
{
int tmp = someValue1;
someValue1 = someValue2;
someValue2 = tmp;
}
class A {
public :
int value;
void inspect(const B& b);
const B& returnConstRef();
private :
int someInt;
B classB;
};
const B& A::returnConstRef()
{
return classB;
}
In the above class, returnConstRef returns a const reference to B. So whatever
we get like this should not be able to change class B like below. Also the
compiler should not allow me to assign a non-const class B (classB) to classA.
returnConstRef().
A classA;
B classB = classA.returnConstRef();
classB.ChangeValue();
With the above code there is no problem with the compiler. I am wrong some where
in my understanding of the returning values by reference, Can somebody please
correct ?
Thanks in advance
KInd.