c++ - Why does this operator overloading work? -


this question has answer here:

i trying learn c++ oop concepts through online tutorial encountered code snippet illustrating operator overloading.

the code shown below:

class myclass{ int var; public:     myclass(int value=0){     var = value;     }      myclass operator+(myclass &obj){     myclass newobj;     newobj.var = this->var + obj.var;     return newobj;     } }; 

suppose call operator in main function so:

int main(){ ... obj3 = obj2 + obj1; ... } 

during earlier tutorials on classes, read why copy constructors require parameters passed reference since definition of how copy 2 class objects. so, far understand, copy constructors must when 1 has copy objects of class.

in above code snippet, appears me compiler try "copy" values of newobj onto l_value in main() function (obj3). how possible without copy constructor defined. have misunderstood here?

thank help!

http://en.cppreference.com/w/cpp/language/copy_constructor#implicitly-declared_copy_constructor

if using standard c++ 2003 or older copy constructor implicitly defined (generated compiler) class t unless:

  • t has non-static data members cannot copied (have deleted, inaccessible, or ambiguous copy constructors);
  • t has direct or virtual base class cannot copied (has deleted, inaccessible, or ambiguous copy constructors);
  • t has direct or virtual base class deleted or inaccessible destructor;

if using standard c++ 2011 or newer copy constructor implicitly defined (generated compiler) class t unless:

  • t has non-static data members cannot copied (have deleted, inaccessible, or ambiguous copy constructors);
  • t has direct or virtual base class cannot copied (has deleted, inaccessible, or ambiguous copy constructors);
  • t has direct or virtual base class deleted or inaccessible destructor;
  • t has user-defined move constructor or move assignment operator;
  • t union , has variant member non-trivial copy constructor;
  • t has data member of rvalue reference type.

also keep in mind that

a = b; 

is not calling copy-constructor copy-assignment. in turn implicitly defined (auto-generated) if class if suitable.

for details see: http://en.cppreference.com/w/cpp/language/copy_assignment#implicitly-declared_copy_assignment_operator


Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -