Code:

#include <iostream> #include <cstdlib> using namespace std; class myclass { public: int var; myclass(int i) { cout << "Obuchnuy konstructor.\n"; var = i; } myclass(const myclass &obj) { cout << "Konstructor kopii.\n"; cout << "Kk: " << obj.var << endl; } ~myclass() { cout << "Destructor.\n"; } }; myclass f() { myclass ob(5); cout << ob.var << endl; return ob; } int main() { myclass a(10); cout << a.var << endl; a = f(); cout << a.var << endl; system("pause"); return 0; } 

MVS 2013 Conclusion:

 Obuchnuy konstructor. 10 Obuchnuy konstructor. 5 Konstructor kopii. Kk: 5 Destructor. Destructor. -858993460 

Those. The copy constructor returned the garbage to main ().

If you compile with mingw and the -fno-elide-constructors key (otherwise the copy constructor is ignored), the output is almost the same, only the garbage is different.

The question is why?

  • 3
    you left only the print in the copy constructor, but there is no copying of the object itself, so when you exit the function after calling the copy constructor, the garbage returns. - cybrex

1 answer 1

Your copy constructor does not copy the data members of the constructor argument object.

 myclass(const myclass &obj) { cout << "Konstructor kopii.\n"; cout << "Kk: " << obj.var << endl; } 

It only outputs to the console the value of the data member var of the argument object of the constructor. The constructor should look like this:

 myclass(const myclass &obj) : var( obj.var ) { cout << "Konstructor kopii.\n"; cout << "Kk: " << obj.var << endl; } 

Note that you should explicitly define the copy assignment operator. According to the current C ++ standard (12.8 Copying and moving class objects)

18 If the class definition is not explicitly declare a copy assignment, it’s not. If a class is defined as a declaration, it is a declaration; otherwise, it is defined as defaulted (8.4). The latter is the case of a user-declared constructor or a user-declared destructor .

  • Thank you, another question, is it possible to say that the copy constructor in my program is called to create the object 'a' here: a = f (); ? - Lurking Elk
  • @Dim Team This clause uses a copy assignment operator defined implicitly by the compiler, since object a has already been created. - Vlad from Moscow
  • one
    @DimTeam, the copy constructor can be called in this line (if there is no displacement constructor and NRVO did not work). After that, an assignment statement will be called (either copying or moving (if it is redefined)) - ixSci
  • @ixSci The class has neither a motion constructor nor a motion operator. - Vlad from Moscow
  • @VladfromMoscow, I see, but it's good for the author to know, I think. I used the words "if." - ixSci