You must write a function Get () (Get ()). The number of designers is not equal to the number of destructors.

#include <iostream> class Coord { private: double x, y; public: Coord(double _x = 0, double _y = 0) : x(_x), y(_y) { x = _x; y = _y; std::cout << "Constructor is run" << std::endl; } ~Coord() { std::cout << "Destructor is run" << std::endl; } void Show() { std::cout << "x = " << x << " y = " << y << std::endl; } Coord Get() { return *this; } Coord& operator = (Coord obj) { x = obj.x; y = obj.y; return *this; } }; int main() { Coord object1(10, 15); object1.Show(); Coord object2; object2 = object1.Get(); object2.Show(); return 0; } 

Tell me, please, what is the error and how to fix it?

    3 answers 3

    Because when calling Coord& operator = (Coord obj) , the object is copied, and you did not override the copy constructor, therefore the compiler itself generated it. You can fix this (do not call the copy constructor) by passing obj by reference, or add the copy constructor:

     Coord(const Coord& rhs) { std::cout << "Copy constructor is run" << std::endl; } 

      There is no error; when you call Get an implicitly defined copy constructor works for which there is no logging.

        As already mentioned in other answers: the problem lies in the lack of definition of a custom implementation of the copy constructor.

        On this account in C ++ from time immemorial there is a so-called "Rule of Three" , which states that if a class or structure defines one of the following methods, then they must explicitly define all three methods:

        • Destructor
        • Copy Constructor
        • Copy Assignment Operator

        In addition, several code recommendations:

        • Resetting the values ​​for x , y not required, since already running in constructor initializer.
        • Member functions that do not change the visible state of an object ( Show , Get ) should be declared with the const keyword:

           Coord Get() const; 
        • Passing the argument to the copy assignment operator in the canonical version should be done via the constant reference const Coord& obj . In general, the variant and transmission by value is possible, for example, when implementing the "copy-and-swap" idiom.