Reputation: 182
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.
Upvotes: 2
Views: 84
Reputation: 118340
You can use a braced initialization list to invoke the constructor:
calcSum({5, 3});
A somewhat broad term for this feature of C++ is called "implicit conversion". If the type of the object being "assigned to" (or constructed, which in this case is a function parameter) does not match the type of the object being "assigned from", C++ has a long, long list of rules of implicit conversions that can be used to convert one type to another.
One of these rules involves a comma-separated list of values in braces. If it is specified for an object with an explicit constructor, the constructor get used to construct the object.
Note that this also invokes the same constructor as in the original code:
calcSum({5});
A constructor with one parameter does not need braces to be implicitly invoked.
Upvotes: 4