0

I am trying to learn C++ OOP concepts through an online tutorial where I encountered a code snippet illustrating operator overloading.

The code is 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 I call the operator in the main function like so:

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

During earlier tutorials on Classes, I read about why copy constructors require all parameters to be passed by reference since they themselves are the definition of how to copy two class objects. So, as far as I understand, copy constructors are a must when one has to copy objects of a class.

In the above code snippet, it appears to me that the compiler will try to "copy" the values of newobj onto the L_value in the main() function (obj3). But how is this possible without a copy constructor defined. Have I misunderstood something here?

Thank you for your help!

1 Answers1

0

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

If you are using standard C++ 2003 or older copy constructor is always implicitly defined (generated by compiler) for any class T unless:

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

If you are using standard C++ 2011 or newer copy constructor is always implicitly defined (generated by compiler) for any class T unless:

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

Also keep in mind that

a = b;

is not primarily calling copy-constructor but copy-assignment. That in turn is also implicitly defined (auto-generated) if your class if suitable.

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

Jan Korous
  • 666
  • 4
  • 11