Saturday 15 May 2010

c++ - Constructor Call Within Different Constructor Yields Erroneous Data -


The following is the smallest program that replicates my problem:
  #include & Lt; Iostream & gt; using namespace std; Classroom test {public: test () {_a = 0; } Test (int t) {test (); _b = t; } Zero performance () {cout & lt; & Lt; _a & lt; & Lt; '' & Lt; & Lt; _b & lt; & Lt; Endl; } Private: int _a; Int _b; }; Int main () {Test Test (10); Test.Display (); // 70 10 return 0; }   

When I do this, with the password _a starts, why does this happen? Is there any problem when the constructor is implemented from within another?

The problem here is in this code:

  test (int t ) {Test (); _b = t; }   

This calls the no default test constructor, then set _b = t . Instead, it creates a temporary object of type test using the default constructor, ignores that temporary object, then sets _b = t as a result, default The constructor will not run for the receiver object, so the _a will remain unregistered.

To fix this, in C ++ 11, you

  test (int t): test () {_b = t; }   

which calls the default constructor, or (in C + 03 03) you can distinguish the initialization code from a default constructor into a supporting member function that you call by default Are and Parameter Manufacturers:

  Test () {defaultInit (); } Test (int t) {defaultInit ()); _b = t; }   

Or, if you have the C ++ 11 compiler, then eliminate the default constructor using the default starters, like:

  class test {Public: test () = default; Test (int t) {_b = t; } Zero performance () {cout & lt; & Lt; _a & lt; & Lt; '' & Lt; & Lt; _b & lt; & Lt; Endl; } Private: int _a = 0; Int _b; };   

Hope it helps!

No comments:

Post a Comment