user10761235
user10761235

Reputation:

Why won't my function pass the correct value?

I have a zybooks section that has a challenge that is killing me. The following only code i can change is the createlicenseNum function.

 #include <iostream>
using namespace std;

class DogLicense{
   public:
      void   SetYear(int yearRegistered);
      void   CreateLicenseNum(int customID);
      int    GetLicenseNum() const;
   private:
      int    licenseYear;
      int    licenseNum;
};

void DogLicense::SetYear(int yearRegistered) {
   licenseYear = yearRegistered;
}

// FIXME: Write CreateLicenseNum()

void DogLicense::CreateLicenseNum(int customID) {
   int licenseNum;
   int licenseYear;
   licenseNum = 0;
   licenseNum = (100000 * customID) + licenseYear;

}


int DogLicense::GetLicenseNum() const {
   return licenseNum;
}

int main() {
   DogLicense dog1;

   dog1.SetYear(2014);
   dog1.CreateLicenseNum(777);
   cout << "Dog license: " << dog1.GetLicenseNum() << endl;

   return 0;
}

The problem is that the output when GetLicenseNum() is ran, the output is 0. I tried adding in a cout to the createlicenseNum function to see what licenseNum equals when its ran and I get a nonzero number, but it is not correct. I know the problem, I think, is with the passing of variables, but I am lost at how to fix it.

Upvotes: 0

Views: 337

Answers (1)

Mobile Ben
Mobile Ben

Reputation: 7341

Change to this

void DogLicense::CreateLicenseNum(int customID) {
    licenseNum = (100000 * customID) + licenseYear;

}

You are creating shadowed variables in your existing CreateLicenseNum. This means that licenseNum and licenseYear are locally scoped to CreateLicenseNum. The local licenseNum and licenseYear are not initialized to a specific value, so licenseYear can be anything.

Upvotes: 1

Related Questions