initialization list

G

giuseppe.on.usenet

class MyClass {
public:
MyClass(int a = 0) : var(a) { };
private:
int var;
};

int main() {
/* why can I use the initialization list here? */
MyClass myArray[2] = {1, 2};
}


Obviously int myArray[2] = {1, 2} would have been correct, but I don't
understand why MyClass myArray[2] is correct as well.
 
J

Juha Nieminen

giuseppe.on.usenet said:
Obviously int myArray[2] = {1, 2} would have been correct, but I don't
understand why MyClass myArray[2] is correct as well.

Why shouldn't it be correct? If you want to get an error, try making
the constructor explicit.
 
S

Saeed Amrollahi

class MyClass {
public:
    MyClass(int a = 0) : var(a) { };
private:
    int var;

};

int main() {
    /* why can I use the initialization list here? */
    MyClass myArray[2] = {1, 2};

}

Obviously int myArray[2] = {1, 2} would have been correct, but I don't
understand why MyClass myArray[2] is correct as well.

Hi

I believe it's OK.
you have a similar case like this:
MyClass c = 1; // convert int to MyClass.
// compiler implicitly call conversion constructor
Now, we have initializer list of integers. So for each initializer,
compiler calls the conversion constructor.

HTH,
-- Saeed Amrollahi
 
A

Andrey Tarasevich

class MyClass {
public:
MyClass(int a = 0) : var(a) { };
private:
int var;
};

int main() {
/* why can I use the initialization list here? */
MyClass myArray[2] = {1, 2};
}


Obviously int myArray[2] = {1, 2} would have been correct, but I don't
understand why MyClass myArray[2] is correct as well.

It is correct because the language specification says it is correct. Your

MyClass myArray[2] = {1, 2};

is interpreted as

MyClass myArray[2] = { MyClass(1), MyClass(2) };
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top