Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this ambiguous or is it perfectly fine?

Is this code ambiguous or is it perfectly fine (approved by standards/has consistent behavior for any compilers in existence)?

struct SCustomData {
    int nCode;
    int nSum;
    int nIndex;
    SCustomData(int nCode, int nSum, int nIndex)
        : nCode(nCode)
        , nSum(nSum)
        , nIndex(nIndex)
    {}
};

edit:
yes, I am referring to the fact that the member variables have the same name with formal parameters of the constructor.

like image 707
Afriza N. Arief Avatar asked Jan 29 '10 10:01

Afriza N. Arief


2 Answers

No, in this case there are no ambiguity, but consider following:

struct SCustomData {
//...
    void SetCode(int nCode)
    {
            //OOPS!!! Here we do nothing!
            //nCode = nCode;

            //This works but still error prone
            this->nCode = nCode;
    }
};

You should draw attention to one of existing coding styles. For instance General Naming Rule in Google C++ Coding Styles or read excellent book "C++ Coding Standards: 101 Rules, Guidelines, and Best Practices" by Herb Sutter and Andrei Alexandrescu.

like image 78
Sergey Teplyakov Avatar answered Nov 01 '22 08:11

Sergey Teplyakov


Your example is unambiguous (to me), but it's not good practise, because it can quickly become as ambiguous as hell.

It's a long while since I've written any C++ in anger, so I'm guessing what the following will do.
Do you KNOW what it will do? Are you sure?

class Noddy
{
    int* i;
    Noddy(int *i)
    : i(i)
    {
        if(i == NULL)
            i = new int;
    }
};
like image 36
Binary Worrier Avatar answered Nov 01 '22 09:11

Binary Worrier