I stumbled upon this question (which is a different example). And most say a constructor does not return anything. However, why does my example work?
sequence(1, 2)
is a constructor and obviously can be used on my machine. I use g++
and tried without option and with C++11 option. Both work in my case.
The example is from a course. I copy as is, no matter whether public
makes sense or not, or something else.
Example:
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
using namespace std;
void printer(int i) {
cout << i << ", ";
}
struct sequence {
int val, inc;
public:
sequence(int s, int i) : val(s), inc(i) {
cout << "Sequence(" << val << ", " << inc << ")" << endl;
}
operator int() const {//LINE I
int r = val;
cout << r << endl;
return r;
}
};
int main() {
vector<int> v1(7);
fill(v1.begin(), v1.end(), sequence(1, 2)); //LINE II
for_each(v1.begin(), v1.end(), printer);
return 0;
}
Result:
Sequence(1, 2)
1
1
1
1
1
1
1
1, 1, 1, 1, 1, 1, 1,
Update
Thank you all for the answers. But I am still pretty confused, cannot get it into my head, probably missing proper terminology I think.
So far I think I understood:
sequence
is astruct
objectsequence(int, int)
is a constructor definition and does not return anything()
operator onsequence
simply returns theval
value.
So why does it work:
- the call to
sequence(1,2)
creates a temporary object that can be accessed and read - the
()
is used to fill the respective element. basicallyfill
usessequence()
to get the value to fill in. - after
fill
has finished the temporary object is destroyed. It's scope is the scope of the functionfill
Does that sound right so far?