I'm currently reading about C++, and I read that when using return by reference I should make sure that I'm not returning a reference to a variable that will go out of scope when the function returns.
So why in the Add
function the object cen
is returned by reference and the code works correctly?!
Here is the code:
#include <iostream>
using namespace std;
class Cents
{
private:
int m_nCents;
public:
Cents(int nCents) { m_nCents = nCents; }
int GetCents() { return m_nCents; }
};
Cents& Add(Cents &c1, Cents &c2)
{
Cents cen(c1.GetCents() + c2.GetCents());
return cen;
}
int main()
{
Cents cCents1(3);
Cents cCents2(9);
cout << "I have " << Add(cCents1, cCents2).GetCents() << " cents." << std::endl;
return 0;
}
I am using CodeBlocks IDE over Win7.