Thursday, May 22, 2008

c++: constructor arguments

Names of constructor arguments which will initialize class members can have the same name as class members:

class A
{
    public:
        A(int x) : x(x) {} 

        int x;
};
I used to make a prefix for constructor arguments as thought compiler will produce an error message. Yeah, now source code can be cleaner. Be aware that next code won't work:
class A
{
    public:
        A(int x) {x = x;} 

        int x;
};
Here x in constructor's body is the argument of the contructor. You will have an unexpected value of A::x each time as it not initialized. As a workaround:
class A
{
    public:
        A(int x) {this->x = x;}

        int x;
};
Here x in constructor's body is argument of constructor and this->x is A::x.

2 comments:

Cheba said...

> Here x in constructor's body is A::x.

Do you mean that field (A::x) has greater priority than local variable (argument)?

Ni@m said...

Actually I've made a mistake. Constructor argument has a higher priority than class member. I've updated the post.