c++objectconstructorinstantiationobjectinstantiation

C++ Instantiating "Implicit" Class Object


class Cents
{
private:
int m_nCents;

public:
Cents(int nCents) { m_nCents = nCents; }

// Overload cCents + int
friend Cents operator+(const Cents &cCents, int nCents);
int GetCents() { return m_nCents; }
};

// note: this function is not a member function!
Cents operator+(const Cents &cCents, int nCents)
{
return Cents(cCents.m_nCents + nCents);
}

int main()
{
Cents c1 = Cents(4) + 6;
std::cout << "I have " << c1.GetCents() << " cents." << std::endl;

return 0;
}

It's not clear to me how the expression

Cents(4)+6 

in line

Cents c1 = Cents(4) + 6;

is evaluated. Yeah I know that we're overloading operator "+" for operands of types Cents and int respectively.

As I understand Censt(4) is the constructor, right? So when

Cents operator+(const Cents &cCents, int nCents)
 {
 return Cents(cCents.m_nCents + nCents);
 }

is called does cCenst become a reference to Cents(4)?

From the line

return Cents(cCents.m_nCents + nCents);

one can deduce that cCenst is an object of type Censt since we access m_nCents via member selection operator "." But Censt(4) is a constructor and not a class object.

To me it doesn't seem to make sense for cCenst to be a reference to Cents(4) since they're not equivalent.


Solution

  • As I understand Censt(4) is the constructor, right?

    No, not quite. You never call a constructor directly, even though this syntax makes it kind of seem like you do.

    Here you're constructing a temporary of type Censt with constructor argument 4.

    Think of it more like this:

    Censt x(4);  // creates a `Censt` with name `x` from argument `4`
    Censt(4);    // creates a `Censt` with no name from argument `4`
    

    It's not a function call.

    does cCenst become a reference to Cents(4)?

    Yes.

    But Censt(4) is a constructor and not a class object.

    Again, no. It is an object.