Whats this called?

This topic is 4814 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

struct A{
A(int i):i(i){}
int i;
};
struct B{
B(A a):a(a){}
A a;
};
int main() {
B b(1);
return 0;
}


b.a.i is equal to 1 I'm using mingw 3.4.2 and I've heard mention of stuff like this being done. Does anyone know the name of this feature and can it be expanded in any way? Passing in only one value can be restricting. Or, is this a terrible obfustication of C++?

Share on other sites
Its pretty weird, but its legal. It will just initialize B's "A" structure so that it has its "i" value equal to one. Kind of obfuscated, but it doesn't matter really cause it gets the job done well, cleanly, and in one line of code. Just make sure to comment it!

A(int new_i)
: i(new_i) //This part??

Share on other sites
Are you refering to the "Initialization Lists"?

It's a normal, standard feature. It allows you to call specific constructors for member variables before entering the constructor itself (which is faster if the compiler dosn't optimise some things), as well as calling specific constructors on the object's parent (which can't be done any other way).

Share on other sites
Sorry for not being so clear. Its not the initializer lists. I use them regularly.
I was wondering about the passing of a value and having it automatically constructed and then passed to the function.

Does this have a proper name?

Share on other sites
Oh, ok [smile].

What you are refering to is called an "implicit conversion" (the integer 1 is implicitly converted to an object of type A).

If you want to avoid it, put the keyword "explicit" in front of your constructor for A.

Share on other sites
Ahh, cool. Actually I was wondering if there is anyway I can expand on implicit conversion. Is there anyway I can pass more than one parameter or is that the extent of this feature?

Share on other sites
afaik, it's virtually interchangeable with
B b=1;
Although in the code you posted there is no call to the assignment operator, thus no copying takes place. It should be slightly more optimal in general I think, but wont make a lick of difference in this case.

Share on other sites
Quote:
 Original post by aaron_dsAhh, cool. Actually I was wondering if there is anyway I can expand on implicit conversion. Is there anyway I can pass more than one parameter or is that the extent of this feature?

You can only implicitly convert a single variable. You must explicitly call constructors with more than one argument.

1. 1
2. 2
3. 3
4. 4
frob
15
5. 5

• 12
• 12
• 20
• 12
• 13
• Forum Statistics

• Total Topics
632151
• Total Posts
3004462

×