Michael Hang
Michael Hang

Reputation: 199

Struct Initialization Arguments

I have a struct, player, which is as follows:

struct player {
string name;
int rating;
};

I'd like to modify it such that I declare the struct with two arguments:

player(string, int)

it assigns the struct's contents with those values.

Upvotes: 5

Views: 29847

Answers (4)

kevintodisco
kevintodisco

Reputation: 5181

You are allowed to declare a constructor for your player struct:

struct player {
    string name;
    int rating;

    player(string n, int r) :
        name(n),
        rating(r)
    {
    }
};

In C++ one of the few differences between classes and structs is that class members default to private, while struct members default to public.

Upvotes: 4

egrunin
egrunin

Reputation: 25053

Although (as has been pointed out), you can simply add a constructor:

struct player() {
    string name;
    int rating;
    player(string Name, int Rating) { 
        name = Name; rating = Rating; 
    }
}; 

Is there some reason you don't want to make it a class?

class player() {
public:
    string name;
    int rating;
    player(string Name, int Rating) { 
        name = Name; rating = Rating; 
    }
}; 

Upvotes: 5

ildjarn
ildjarn

Reputation: 62975

Aside from giving your type a constructor, because as-shown it is an aggregate type, you can simply use aggregate initialization:

player p = { "name", 42 };

Upvotes: 8

justin
justin

Reputation: 104698

you would use the constructor, like so:

struct player {

  player(const string& pName, const int& pRating) :
    name(pName), rating(pRating) {} // << initialize your members
                                    //    in the initialization list

  string name;
  int rating;
};

Upvotes: 8

Related Questions