Does the operation on "this" pointer calls the constructor ?
I have a constructor defined as follows
Cents(int cents)
{
cout<<"in cents constructor\n";
m_cents = cents;
}
friend Cents operator + (const Cents &c1, const Cents &c2)
{
return Cents(c1.m_cents + c2.m_cents);
}
Cents operator ++ (int)
{
cout<<"In c++ function\n";
Cents c(m_cents);
*this = *this + 1 ;
return c;
}
in main function I have sth like...
Cents c;
cout<<"Before post incrementing\n";
c++; //This part is calling the constructor thrice
Now If I am doing some operation like *this = *this + 1
.
It calls this constructor twice.
What exactly is going on here. Does *this
creates a temp object and assigns the value to the original object?
No, dereferencing a pointer doesn't create any new object.
Hovever, if you have operator+
defined only for instances of your class, there will be a new instance constructed from 1
, because the constructor Cents(int cents)
isn't marked as explicit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With