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.
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.
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;
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With