Jacob
Jacob

Reputation: 1

How to call a specific constructor function that takes an array of strings as the argument?

I'm having a little difficulty in calling a class constructor in the int main() part of my code. It is a constructor with an array of strings as the argument.

I know that, when calling a constructor, one can either set default arguments or no arguments at all, and that an object is required to call the constructor (along with the arguments, we want to give in it). But I still don't understand how to call this, although I've tried many different methods.

This is my code:

#include <iostream>
#include <string>

using namespace std;

enum player_position{ GoalKeeper, Midfielder, Defender, Striker };

class Football_Player
{
private:
    string Name;
    int Age;
    int Points;
    player_position Ppos;

public:
    Football_Player(string _name = "aname", int _age = 20, int _points = 50, player_position _ppos = Striker)
    {
        Name = _name;
        Age = _age;
        Points = _points;
        Ppos = _ppos;
    }

    Football_Player(string str[4])    // <---- "This Constructor is the one , i can't seem to call into the main()."
    {
        cin >> str[0];
        Name = str[0];
        cout << Name;
        cout << str[0];
        int a = atoi(str[1].c_str());
        cout << a;
        int b = atoi(str[2].c_str());
        cout << b;
        str[3] = Ppos;
    }
};

int main()
{

    // Please don't take any of the info as biased, these are just random.

    Football_Player("Messi", 20, 50, Striker);// This one is the previous constructor with the default arguments and this one seems to be working.  


    Football_Player ();    // Trying to call that constructor
    Football_Player object1("Messi");  // Trying to call that constructor
    Football_Player object2("Ronaldo", 25, 50, Striker);    // Again trying to call that Constructor
    Football_Player object3(str[0]);    // And Again . . . . 

    system("pause");
    return 0;
}

Upvotes: 0

Views: 91

Answers (1)

St0fF
St0fF

Reputation: 1633

As you declared 4 defaults in your first CTor, your call Football_Player object1("Messi"); will actually call that one, and leave

age = 20
points = 50
position = Striker

It's plain wrong that you "either must give all params, or none". For all arguments you give, position matters. In your example: If you give 2 arguments, you give the name and the age. There is no way to give points and position only. Also a call like Football_Player object1("Messi",,,Midfield); is not possible.

The second constructor always needs an array of 4 strings. Nothing more, nothing less. But I would recommend to remove that one, as with no tricks you could also give it a pointer to a string, resulting in a crash.

Upvotes: 1

Related Questions