Design issue.

Hey guys,

I have an exercise that wants me to identify the design issue with this code snippet.

I'm a little unsure as to what the design issue is? It functions correctly. I'm guessing it's because the GetHunger prototype is returning m_Hunger in the class? Also the data member m_Hunger hasn't been initialized?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  #include <iostream>

using namespace std;

class Critter 
{
 public:
   int GetHunger() const {return m_Hunger;}
 private:
   int m_Hunger;
};

int main() 
{
  Critter crit;
  cout << crit.GetHunger() << endl;
  return 0;
 }



Thanks for any help.
Last edited on
Heed this answer with a grain of salt, for I could be entirely wrong and I pray someone corrects me if I am, but in my attempt to be helpful.

My speculation is that GetHunger() is a public class, but m_Hunger is a private class, which I think means that m_Hunger can not be changed and therefor constant, but I would imagine that the Hunger of said critter would vary over time?

I only say that because under the private class m_Hunger isn't a constant, which why leave it open to change if it isn't meant to be?


-- Again I apologize if I am dead wrong :|
Thanks for replying!

No I think you're right, the value of m_Hunger will change depending upon certain situations hence why it's not been declared with a default value.

I'm guessing the problem comes down to bad design within the class; I THINK the issue surrounds returning a data member that hasn't been initialized to any value yet? Possibly GetHunger is declared and initialized within the class?
Last edited on
Everything is correct in the code. What the problem is is that there is no constructor initializing the member data to a known state. What you'd be printing are garbage values.

The GetMember() function defined as const is a good thing. It means that you cannot alter the data member's value inside that function.

Joe - C++ tutor
Hey Joe,

So I should write a constructor that initializes m_Hunger like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

using namespace std;

class Critter {
public:
	Critter(int food = 0);
	int GetHunger() const {return m_Hunger;}
private:
	int m_Hunger;
};

Critter::Critter(int food) :
m_Hunger(food)
{}

int main() {
	Critter crit;
	cout << "My hunger level is: " << crit.GetHunger();

}
Right. :)
Topic archived. No new replies allowed.