Search code examples
c++11syntaxconventions

Proper ways to initialize member variables with identical names as the parameters


I got a class that looks like this

class Rational{
    public:
        Rational(int p = 0, int q = 1) : p(p), q(q){};
    private:
        int p;
        int q;
};

My question is about the initialization syntax where member variables and constructor parameters has identical names. I now know it is legal to do so, but my question is: If I want do have "clean", easy to grasp code I wonder if I can do as one normally would do in java:

//Legal Java Code
this.q = q;
this.p = p;
//Is any of these legal C++ code (if so, which one)?
this.q(q);
this.p(p);
//or
this->q(q);
this->p(p);

Even though I haven't tested it, and I can test it, I still want to know the C++ conventions of doing this.


Solution

  • In C++, you have to say:

    this -> q = q;
    this -> p = p;
    

    or equivalently

    (*this).q = q;
    (*this).p = p;
    

    But I think the member initializer list syntax

    Rational(int p = 0, int q = 1) : p(p), q(q){}
    

    is cleaner (note the lack of a semicolon!) Why don't you like it?