Reputation: 35
Table::Table(int n): maxGuests(n)
{
int numGuests = 0;
}
int Table::maxOccupancy(void)
{
return maxGuests;
}
int Table::currentOccupancy(void)
{
return numGuests;
}
As in the above code, I'm getting an unused numGuests
warning, even after returning it at the end of my accessor. Why would that be?
Thanks :)
Upvotes: 3
Views: 2916
Reputation: 3686
In the code
Table::Table(int n): maxGuests(n)
{
int numGuests = 0;
}
A local variable numGuests
is defined, which is not the class property. And this is not used anywhere. Hence you are getting the warning.
Remove int
in the statement int numGuests = 0;
should resolve this problem.
OR better you can update your code to include this property in the initializer list itself like:
Table::Table(int n) : maxGuests(n), numGuests(0)
{
}
Upvotes: 9
Reputation: 45474
The local variable numGuests
in the snippet
Table::Table(int n): maxGuests(n)
{
int numGuests = 0;
}
has not been used. Presumably you want instead
struct Table
{
...
int numGuests = 0; // default value
const int maxGuests;
Table(int n) : maxGuests(n) {}
};
Upvotes: 8
Reputation: 211700
You're creating a variable that "shadows" the property you're trying to assign. I'm not sure why you're using two completely different initialization methods here, but you can simplify the code and fix the bug like this:
Table::Table(int n) : maxGuests(n), numGuests(0)
{
}
Whenever practical, initialize your properties like that. Doing it in code is usually reserved for cases where it's not clear what value will be assigned, some computation is required, or you need to delegate to a function to do it.
Upvotes: 4
Reputation: 241
You create a local variable with the same name as a class member. Just remove int
to get what you want:
Table::Table(int n): maxGuests(n)
{
numGuests = 0;
}
Upvotes: 4