I have a class called Stack. I've implemented the copy constructor but for the copy assignment constructor I just have it call the copy constructor since the logic is the same. But for some reason it just returns a default constructed object. I don't understand why.
The copy constructor:
Stack::Stack( const Stack& s )
{
if ( s.Empty() )
{
this->entry = nullptr;
}
else
{
this->entry = new Entry();
Entry* i = this->entry;
for ( Entry* p = s.entry; p != nullptr; p = p->next )
{
i->number = p->number;
i->next = p->next == nullptr ? nullptr : new Entry();
i = i->next;
}
}
}
The copy assignment constructor:
Stack& Stack::operator=( const Stack& s )
{
return Stack( s );
}
The calling code:
Stack s;
s.Push( 5 );
s.Push( 3 );
Stack s2;
s2 = s; //s2 just ends up defaulted constructed instead of copied from s
If I replace the lines:
Stack s2;
s2 = s;
with:
Stack s2(s);
everything works just fine. What am I doing wrong here?
EDIT --
So the lesson here is to implement the assignment ctor and leverage that in the copy ctor, not the other way around as I had done.