Search code examples
c++arraysconstructorifstream

Passing ifstream as an argument to a class constructor


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?


Solution

  • 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};