-2

I just learned how to create a class or object in C++ and I'm practicing and learning.

I'm writing a text based version of a popular board game and I was wondering if it's overkill creating a class for six sided dice instead of creating a simple function generating two random numbers between 1 and 6 and returning the sum of the two.

gnat
  • 20,543
  • 29
  • 115
  • 306

2 Answers2

2

C++ supports several programming paradigms (including);

  • OO based techniques
  • Generic and template programming
  • Procedural style programming (coming from C)

Using any of these techniques where is appropriate is not going to be "overkill". The broader question is more what design or pattern would be appropriate for the problem being solved, given the context of the current implementation and domain specific constraints?

Since you are looking at this from a learning exercise, creating a class for dice would be fine, the object maps well to a physical thing - so go for it.

Would I create a class in a production application if all I wanted was two random numbers - maybe. I would use a function that returned a std::pair (std::pair<int,int> get_random(...)) and either provide the functions with the appropriate engine and distribution requirements as arguments, else have those arguments in an object to assist with the state management.

Niall
  • 1,851
0

... overkill creating a class for six sided dice instead of creating a simple function generating two random numbers between 1 and 6 and returning the sum of the two.

As ever, it depends.

You don't say which game you're implementing, but are you only ever going to use 6-sided dice? If so, then stick with a function. If you want to go all "OO" with this then, as it stands, you could make this function into a static method on a helper class.
But, if you wanted to add 'D10's and 'D20's into the mix later on, then a class might be a far better starting point.

Phill W.
  • 13,093