Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

*this makes a call to constructor?

Tags:

c++

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?

like image 954
Kundan Kumar Avatar asked Apr 22 '12 10:04

Kundan Kumar


1 Answers

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.

like image 117
Rafał Rawicki Avatar answered Sep 23 '22 06:09

Rafał Rawicki