Return a reference by a class function and return a whole object in c++? -
operator overloading in class cvector:
cvector cvector::operator+ (cvector param) { cvector temp; temp.x = x + param.x; temp.y = y + param.y; return (temp); } and in main:
cvector (3,1); cvector b (1,2); cvector c; c = + b; so object passed value, , temp object being created. guess b being passed value, 1 calling + therefore x , y belong , pram.x , param.y b. temp returned , the copy assignment operator delivers temp's values c?
but this:
cvector& cvector::operator= (const cvector& param) { x=param.x; y=param.y; return *this; } and in main:
a=b; again calling = , b being passed reference const.(in case matter if passed value?) confused, x belonging assigned param.x of be. why isn't function void, since x , y can accessed function. return *this means, know address of object calling function, *this function itself, if returning object need assign it somewhere previous c=temp after temp=a+b? , cvector& mean, doesn't expecting address of object of cvector type?
in other words why isn't function just:
void cvector::operator= (const cvector& param) { x=param.x; y=param.y; } ??
then there code
#include <iostream> using namespace std; class calc { private: int value; public: calc(int value = 0) { this->value = value; } calc& add(int x) { value += x; return *this; } calc& sub(int x) { value -= x; return *this; } calc& mult(int x) { value *= x; return *this; } int getvalue() { return value; } }; int main() { calc ccalc(2); ccalc.add(5).sub(3).mult(4); cout << ccalc.getvalue(); return 0; } now if removed & functions:
calc add(int x) { value += x; return *this; } calc sub(int x) { value -= x; return *this; } calc mult(int x) { value *= x; return *this; } and used
calc ccalc(2) ccalc.add(5); ccalc.sub(3); ccalc.mult(4); instead of former, produce same resault. why calc& returne type allow chaining.
i not want know how program, since object oriented writing pattern (this written this, needed if that) opposed structured programming have use logic, know why peace of code defined is, , why isn't intuitively think should be(although learn programming year).
thanks!
so why isn't function void, since x , y can accessed function. return *this means
since operator=() declared return reference, return *this; returns reference current object. allows chain assignment operators. example,
a = b = c; will call b.operator=(c); , return reference b. a assigned call equivalent a.operator=(b).
Comments
Post a Comment