0

I am trying to use an ifstream object as an argument to a class constructor so that I can instantiate an array of objects. Currently I have the following in my header:

class Animal
{
private:
    string name;
    int portions;
    int rarity;
    int habitat;
    int climate;
public:
Animal(ifstream &animalInput)
{
    getline (animalInput, name, '\n');
    animalInput >> portions;
    animalInput >> rarity;
    animalInput >> habitat;
    animalInput >> climate;
    animalInput.ignore(numeric_limits<streamsize>::max(), '\n');
}
};

And in my main.cpp:

const int numberOfAnimals = 12;
ifstream animalInput;
    animalInput.open ("animals.txt");
    if (animalInput.fail())
    {
        cout << "Opening file animals.txt failed";
        exit(1);
    }
Animal animals[numberOfAnimals](animalInput);

I am getting the error that no suitable conversion function from "std::ifstream" to "animals[12]" exists. My code then fails to compile because I do not have a default constructor. Am I passing ifstream incorrectly or is what I am trying to do impossible?

jacisback
  • 5
  • 3

1 Answers1

0

When you create an array of objects, the default constructor is used to initialize the objects unless you provide the objects to initialize with in the initialization list.

You can use:

Animal animals[numberOfAnimals] = {Animal(animalInput), Animal(animalInput), ... 12 times };

However, given how you are using animalInput in the constructor, it won't work for you. You should create a default constructor to get around the problem. Then, you can use:

Animal animals[numberOfAnimals] = {Animal(animalInput)};

When this is used, the first object of the array will be constructed with data from animalInput. All other objects will be constructed using the default constructor.

The other option is to create a single object by reading the data from the file and then use that object to initialize the elements of the array.

Animal prototype(animalInput);
Animal animals[numberOfAnimals] = {prototype, prototype, ... 12 times};
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Thanks for the help. So from what I understand there is really no way to use a constructor to quickly assign all the elements of an array of objects values from a file? – jacisback Dec 24 '14 at 18:15
  • Ah that option seems useful. How about if I wanted each element of the object array to have different values that are present by reading further along in the file? It would require multiple single object prototypes like you gave for example correct? – jacisback Dec 24 '14 at 18:30
  • If the file has data for all the objects, you can initialize the array using my first suggestion. If it has data only for `3` objects, then you can use `{Animal(animalInput), Animal(animalInput), Animal(animalInput)}` and leave the rest of the elements of the array to be default constructed. – R Sahu Dec 24 '14 at 18:35