-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
  • 21,442
  • 29
  • 112
  • 288
  • 4
    The answer to the title of your question is "Yes, of course." The answer to the body of your question is "it depends on whether or not you need to encapsulate state or behavior beyond a simple function." If you *only* need to generate two random numbers and add them together, you probably don't need a class for that. – Robert Harvey Aug 04 '15 at 05:13
  • int main() { cout << "Hello World!; } I'd not create a class for that. But anything much more complex, it's probably a good idea :) – jwenting Aug 04 '15 at 05:38

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,831
  • 1
  • 18
  • 20
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.
  • 11,891
  • 4
  • 21
  • 36