Kundan Kumar
Kundan Kumar

Reputation: 2002

*this makes a call to constructor?

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?

Upvotes: 8

Views: 226

Answers (2)

johnsyweb
johnsyweb

Reputation: 141918

You've a whole lot of contsructions going on here!

Cents c;

This line calls Cents::Cents(), which is synthesised by the compiler and may not do what you want it to.

Then you call:

Cents Cents::operator++(int)

Which returns an object and explicitly makes a call to Cents::Cents(int).

Then you do your curious assignment, which makes the second call to Cents::Cents(int) for the second argument.

When you call Cents operator+(const Cents&, const Cents&) you explicitly construct a new one Cents::Cents(int) and return a copy of it...

Then you call the synthesised Cents& Cents::operator=(const Cents&), which again may not do what you want it to.

A typical post-increment operator would look like this:

Cents& operator++(int)
{
    Cents rv = *this;

    ++m_cents;

    return rv;
}

Notice how it returns the value of the class as it was before the increment by calling the copy constructor (rather than an override) and also how it increments the members of the class individually.

Upvotes: 3

Rafał Rawicki
Rafał Rawicki

Reputation: 22690

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.

Upvotes: 11

Related Questions