Can you set an initialization constructor and use another for loading values from file?

Im working on a load file function and in my main program i have a constructor for my player that sets them up, and then in the switch statement in the while loop, I have an option to load from file, and I was thinking a constructor would work for setting the values but it doesnt. Can you even do something like that? I dont really want to create a bunch of setters if I dont have to.

Load function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
vector<int> Load(Player& Hero)
{
    vector<int> loadedData(6);

    ifstream load("monster fight.txt");


	load >> loadedData[0];
    load >> loadedData[1];
    load >> loadedData[2];
    load >> loadedData[3];
    load >> loadedData[4];

	return loadedData;
}


Switch statement case

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
case 4:
            {
                if (Load(Hero).size() == 0)
                {
                    cout << "No data could be loaded from file" << endl;
                }
                else
              
                    cout << "Data restored" << endl;
                
                    Player Hero
                    (
                        "Disaster Chief",
                        init.health = Load(Hero)[0],
                        init.maxHealth = 100,
                        init.money = Load(Hero)[1],
                        init.experience = Load(Hero)[2],
                        init.level = Load(Hero)[3]
                    );
            }
Last edited on
Hello Ch1156,


and then in the switch statement in the while loop, I have an option to load from file, and I was thinking a constructor would work for setting the values but it doesnt.


A constructor for what a class, struct or vector?

If an object has been defined either the default ctor or overloaded ctor has already been called. You can not call a different ctor just because you have new information to store. you would need a function to do this.

On the other hand if you want to input from a file and use that to call an overloaded ctor and create the object after the file is read that would work.

Andy
Hi yes it is a class constructor, sorry for leaving that out. I could use some functions but I wanted to see if there was another way to load the info.

If I created an if statement thatchecked if the game has been played before and if it has then it will load the info in the class constructor, and i not then it creates the constructor thats initialized in main, then would that work?

I'm just trying to find an alternative way to get the data back into the game without having to write a bunch of getters and setters just for loading and saving.
Last edited on
Topic archived. No new replies allowed.