Put a Member Initialization List in a Constructor’s Definition

I have this constructor's definition:

MyClass( int a, int b ): (this->a)(a), (this->b)(b) {}

I thought that would be syntactically correct, but it's apparently not!

Can anyone show me the correct way to that? ( of course, I don't wanna change my arguments' name. :D )

What are the names of your members?
http://www.cplusplus.com/forum/articles/17820/
Well, a and b, of course!

Okay, perhaps I should be more specific.
I have a class like this:
1
2
3
4
5
6
7
class MyClass 
{
const int a;
const int b;

MyClass( int a, int b) : (this->a)(a), (this->b)(b) {}
}


I was trying to initialize a and b using the constructor. But I got some syntax error on line 6! ...
So the question is, how should I fix that?
Last edited on
Why did you put parens around the this->a? I'm not sure what that does but the compiler might be confused into thinking that you are trying to cast into an invalid type. Also I normally use a trailing '_' or 'm_' prefix on member variables and then I don't have to use the this-> to differentiate between the members and the inputs.

Always include the full class declaration in your post when asking these questions. Nobody here can assume what might seem obvious to you after what we have seen in previous posts.
Last edited on
 
MyClass::MyClass( int a, int b ) : a( a ), b( b ) {}


@kempofighter: I put the parens around this->a 'coz I was concerned with the "presedence" issue...

@jsmith: How would C++ ( or rather, the compliler) then differenciate member a and the input a?
How would C++ ( or rather, the compliler) then differenciate member a and the input a?

Because syntax of member initialization is:

MyClass::MyClass(int y1, int y2) : x1( y1 ), x2( y2 ) {}

where x1, x2 are member variables and y1, y2 initialization values (in parenthesis).
Member initialization lists are the one and only one place in the language where the ambiguity
does not exist. The compiler knows that x1( x1 ) means to initialize data member x1 with parameter x1.
This is convenient, because it means that you don't have to think up new names for the parameters.
I must be in the minority, but I find that ugly.

Plus there's still ambiguities if you want to use a member to initialize another member (though granted that's easy to get around)

IMO you should just come up with a new name, or put in an underscore or something. The same name for 2 different things is never a good idea in my book.

</2 cents>
jsmith wrote:
Member initialization lists are the one and only one place in the language where the ambiguity
does not exist. The compiler knows that x1( x1 ) means to initialize data member x1 with parameter x1.
This is convenient, because it means that you don't have to think up new names for the parameters.


That is so cool!
Topic archived. No new replies allowed.