I am currently reading about C ++, and I read that when using return by reference I have to make sure that I am not returning a reference to a variable that will go out of scope when the function returns.
So why in the Add function the cen object is returned by reference and the code is working 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 on top of Win7.
source share