SoftOver
 
Recommended


User login


 

Attributed Argument

   

Please look at the following code and try to find a tiny bug.

#include <iostream>

class SoftwareDeveloper
{
public:
  SoftwareDeveloper(unsigned bugPerThousandLines) 
  : bugsPerThousandLines(bugsPerThousandLines)
  { /*...*/ }
  unsigned GetBugs(unsigned linesOfCode)
  { 
    return linesOfCode*bugsPerThousandLines/1000; 
  }
private:
  unsigned bugsPerThousandLines;   
};

int main()
{
  SoftwareDeveloper JohnDoe(10);
  std::cout << JohnDoe.GetBugs(555) << std::endl;  
}

Did you spot it? The code is perfectly compilable, yet giving unexpected results.
If you think that initialization with the same name does not work – you are wrong, it works, though it is not trivial to see how it works and why.

Try harder, or even try to build it and run. Still puzzled?

























The bug is here:

  SoftwareDeveloper(unsigned bugPerThousandLines) 
    : bugsPerThousandLines(bugsPerThousandLines)

And it works because of

  unsigned bugsPerThousandLines;  

that is just getting initialized with itself.

ALERT! Guideline: Never use the same name for the constructor argument and class attribute.

If the first example was too easy for you – look at the next one. Where is the problem here?

#include <iostream>

class SeniorSoftwareDeveloper : public SoftwareDeveloper
{
public:
  SeniorSoftwareDeveloper(unsigned bugPerThousandLines) 
  : SoftwareDeveloper(bugsPerThousandLines)
  { /*...*/ }
};


int main()
{
  SeniorSoftwareDeveloper JoannaDoe(10);
  std::cout << JoannaDoe.GetBugs(555) << std::endl;  
}

Yes, exactly at the same place. But why the compiler did not complain this time?














Because of another file that you did not see:

class SoftwareDeveloper
{
public:
  SoftwareDeveloper(unsigned bugsPerThousandLines) 
  : bugsPerThousandLines(bugsPerThousandLines)
  { /*...*/ }
  unsigned GetBugs(unsigned linesOfCode)
  { 
    return linesOfCode*bugsPerThousandLines/1000; 
  }
protected:
    unsigned bugsPerThousandLines;   
};

ALERT! Guideline: Never declare protected or public attributes.