EgoObsidian
EgoObsidian

Reputation: 19

overloading operator+ constructor issue

I am learning C++ from a book and I find references and operator overloading really difficult. While studying operator overloading, I can't understand why this program won't work without a constructor that takes an integer as a parameter.

#include <iostream>
using namespace std;

class counter {
public:
    counter();
    counter(int value);
    ~counter();
    int getValue() const { return itsValue;  }
    int setValue(int value) { itsValue = value;  }
    counter operator+(const counter&);
private:
    int itsValue;
};
counter::counter() :
    itsValue(0)
{}
counter::counter(int value) :
    itsValue(value)
{}
counter counter::operator+(const counter& rhs) {
    return itsValue + rhs.getValue();
}
int main()
{
    std::cout << "Hello World!\n";
}

I can't understand why the program won't work in the absence of these lines:

counter(int value);

AND

counter::counter(int value) :
        itsValue(value)
    {}

Upvotes: 0

Views: 59

Answers (1)

cigien
cigien

Reputation: 60238

If you don't have this constructor:

counter(int value);

then you can't do things like:

int n = 3;
counter c = counter{n};
counter c = counter{1};
counter c = 2;
// etc ...

The issue with your operator+ is that you are doing exactly that when you convert the int value itsValue + rhs.getValue() to a counter which is the return type:

counter counter::operator+(const counter& rhs) {
  return itsValue + rhs.getValue();
}

Without the appropriate constructor, there is no way to construct a counter from an int, and you get an error.


You can choose not to provide an int constructor, by manually constructing a counter object, and returning that:

counter counter::operator+(const counter& rhs) const {
    counter c;
    c.itsValue = itsValue + rhs.getValue();
    return c;
}

Note that operator+ should be const-qualified.

Here's a demo.


A few other fixes: setValue should return void. You haven't defined the destructor, but you have provided a declaration. Just remove the declaration, since the implicitly generated destructor is sufficient.

Upvotes: 2

Related Questions