Hello folks!
I am attempting the "Graduation" beginner exercise (
http://www.cplusplus.com/forum/articles/12974/) and am having trouble visualizing how to connect classes. I'm rather new to programming and would appreciate some insight on how to utilize one class in another.
Specifically, I created a NameList class that reads a list of names from a file and stores them in a dynamically-created array. NameList has a public method getRandomName() to return a name from the list selected at random.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
// namelist.h
// NameList reads names from a file and stores them in a list.
#ifndef NAMELIST_H_
#define NAMELIST_H_
#include <fstream>
#include <string>
class NameList
{
private:
static const std::string fileName;
std::string * nameList;
std::ifstream fin;
int listSize;
public:
NameList();
~NameList();
void printList() const;
std::string getRandomName() const; // Return a random name from list
};
#endif
|
I also created a Bunny class to represent each bunny. The constructor initializes various attributes (color, sex, etc), and I want the constructor to utilize the getRandomName() to populate the name field.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
// bunny.h
// Define Bunny class
#ifndef BUNNY_H_
#define BUNNY_H_
#include <string>
#include <iostream>
#include "namelist.h"
class Bunny
{
private:
enum Color {white, brown, black, spotted};
enum Sex {female, male};
NameList nameList; // Problem! New list every time bunny obj created.
std::string name;
Color color;
Sex sex;
int age;
bool radioactive_mutant_vampire;
// ...
public:
Bunny();
Bunny(Color c);
~Bunny();
void showBunny(); // Display bunny info
// ...
};
#endif
|
I'm confident that creating a NameList object in Bunny is a bad design, because it creates a new, identical list every time a Bunny object is created. But I don't know where the NameList should be created instead. I only want one name list in the program so it seems reasonable to add it to main(), but then I can't use nameList.getRandomName() inside the Bunny constructor.
One option is to pass nameList as an argument to Bunny() constructor, but I don't really want the rest of the program to be responsible for that. I feel like it's possible to allow Bunny() constructor to simply call getRandomName(), but don't know how to make that happen. I've read up a bit about singleton classes, static classes and namespaces but don't really understand when they are and are not appropriate. Any advice would be greatly appreciated!
- David G. / EtDecius