Sequence s1 = Sequence();
This creates two Sequence objects. The first is created by Sequence() . The second is created (by copy-building) on Sequence s1 . Or, in other words, this is equivalent to:
const Sequence &temp = Sequence(); Sequence s1 = temp;
Sequence s1 does not create an object reference. He creates an object. Fully formed. You can do:
Sequence s1; s1.show();
And that is wonderful.
If you want to call a constructor other than the standard, just do the following:
Sequence s2(3,"s1");
To understand where this problem came from, look at this version:
const Sequence &temp = Sequence(); Sequence s1 = temp;
You create a Sequence object. This forces the constructor to allocate the array using new . Good.
The second line takes a temporary Sequence object and copies it to s1 . This is called "copy destination."
Since you did not define a copy assignment operator, this means that C ++ will use the default copy algorithm. And this is just a byte copy (it also starts the assignment of a copy of class members). Therefore, instead of the Sequence calling its constructor, it gets the data copied into it from the temporary temp .
Here is the problem. Is source code temporary creation using Sequence() ? It is destroyed when this statement ends. It exists long enough for its contents to be copied to s1 , then it is destroyed.
Destruction means that its destructor is invoked. Its destructor will delete the array.
Now think about what happened. Temporary arose and allocated an array. The pointer to this array was copied to s1 . Then the temporary was destroyed, as a result of which the array was freed.
This means that s1 now contains a pointer to a freed array. This is why bare pointers are bad in C ++. Use std::vector instead.
Also, do not use such copy initialization. If you just want Sequence s1 , just create it:
Sequence s1;