I came across a piece of code that had structs and I am now thoroughly confused about how automatically the constructor of the struct is being called. I made a dummy code just to understand the concept. For example,
struct obj {
int a = 0, b = 2;
obj (int aa) {
a = aa;
}
obj (int aa, int bb) {
a = aa;
b = bb;
}
int getSum () {
return a+b;
}
};
void calcSum (obj o) {
cout << o.getSum() << endl;
}
int main()
{
calcSum(5);
return 0;
}
This does print 7
. I believe that the single argument constructor of struct obj
is automatically being called. If so, how can I make it automatically call the double argument constructor? I am unable to do so.
What is the name of this functionality?
Also please guide me to some good articles as I was unable to find any.
calcSum({12, 34});
Anyway, the term for further research is implicit conversion.calcSum(obj(12, 34))
.explicit
should prevent this BTW. Also see this en.cppreference.com/w/cpp/language/converting_constructorcalcSum({12, 34});
is form (7) in that article.