Question

this is my short code

class A {
public:
    int x,y;
    A(int a=0, int b=0) {
        x=a;y=b;
    }
};
int main() {
    A t[2] = {9,3};
    cout << t[0].x << " " << t[0].y << endl;
    cout << t[1].x << " " << t[1].y << endl;
}

Output is:

9 0
3 0

When i comment my constructor:

9 3
0 0

My question is: why is that? I've tried to overload everything i could figure, that means:copy constructor, constructor with one,two parameters, (coma,equality,[]) operators, but I don't know what compiler generates that it can take 2 integers in one constructor and assign them to x,y. I even tried to overflow numbers in brackets{}, by putting {99999999999999999999,3} to see what compiler will yell but it says it can't convert const int because of overflow, so I believe it must be conversion, but how?

Was it helpful?

Solution

You're implicitly converting 9, and 3 to A.

A small test will prove this:

class A {
public:
    int x,y;
    explicit A(int a=0, int b=0) {
        x=a;y=b;
    }
};

This will yield a compilation error.

That means that your code translates to:

A t[2] = {A(9),A(3)};

Since commenting out the conversion constructor (let's call it that, although I'm not sure it is), it will no longer be able to convert int to A.

The second snippet will only initialize the first element.

EDIT: To clarify, try the following test:

int x[10] = {1,1,1};

This will only initialize the first 3 elements of the array.

Also, without the conversion constructor, try the following:

A t[4] = {1,1,2,2};

The first 2 A's will be initialized.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top