0

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) {} 
2
  • Why do you think the program won't work without those lines? (You're right that it doesn't, but the question should show the full error message) Commented Oct 13, 2020 at 22:21
  • You're also missing the constructor definition Commented Oct 13, 2020 at 22:22

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

"This of course, requires a constructor for counter that takes an int" I think that what OP actually does not understand, I would elaborate this "of course"
@Slava Hmm, not sure how much to edit, but I tried a bit. Is this better?
I mean OP probably does not understand/know that single argument ctor works for type conversion.
@Slava Edited. It should be more helpful now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.