AmatuerCoder101 AmatuerCoder101 - 1 year ago 78
C++ Question

virtual const function not returning initialised value

I have a basic class and header set up relating to an animal, I am trying to have a function which displays an animals current hunger level. Upon testing i have found the hunger level is not at the initial value i have set.


#include "Monkey.hpp"

using namespace std;

Monkey::Monkey() {

unsigned int foodEaten = 0;
unsigned int foodIntake = 800;

unsigned int Monkey::hungerLevel() const {
return (makefoodIntake - foodEaten);


#ifndef MONKEY_HPP
#define MONKEY_HPP

class Monkey : public Animal {
unsigned int foodEaten;
unsigned int foodIntake;

// Overridden to implement the monkey's hunger level
virtual unsigned int hungerLevel() const;

#endif /* end of include guard: MONKEY_HPP */

Why does this not return 800 initially?

Answer Source

Because you did not initialize the members of the class in your constructor.

You have some other variables, with the same name that are declared in the global scope.

However, because you have class members of the same name, the method uses the class members, and not the variables in the global scope.

You need to simply initialize the class members, instead of declaring global variables of the same name:

Monkey::Monkey() : foodEaten(0), foodIntake(800)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download