0
Why double destructor call
What's wrong in this code ? Why two times destructor is called ? https://code.sololearn.com/cYBe2NnYd4Ek/?ref=app
5 Answers
+ 2
statement < myString(); > on line 18, does not call < myString::myString() > on the <this> object,
instead it would construct a temporary local object ( this temporary object has nothing common with the object created by constructor < myString::myString(char const*) > ),
which will then be instantly deleted at the end of the statement. ( hence the first call to the destructor ).
you can use delegating constructor (since C++11) to rewrite your class the following way:
https://www.sololearn.com/compiler-playground/c26P1AaheI2y
+ 1
Itâs called twice because the overloaded constructor creates a new myString object if pInput is a nullptr.
In main you defined char* p to nullptr then called myStringâs overloaded constructor by passing p as a parameter - this created the new myString object using the default constructor - hence the destructor ran twice. Once for both instances of myString.
+ 1
In the overloaded constructor, Initialize your member variables to the same values used in the default constructor. You can change the condition in the overloaded constructor to check if the parameter passed is not a nullptr & perform the appropriate steps. That way you don't have to do anything if a nullptr is passed. The member variables are already initialized just as if you had called the default constructor.
I updated your code to clarify what I mean: https://www.sololearn.com/compiler-playground/cUozOMz4FI0i
0
Great. I missed that part. Got idea like two constructor call resulting into two destructors.
Just curious to know whether there is any mechanism which avoid this ? In other words, how to delegate to empty constructor if we have nullptr?
0
Thanks a ton..!