Question about operator.

Hello! Can anyone explain to me what "Player(const Player &p)" and "Player &operator=(const Player &p)" does? Is the "&operator=" overriding the p? I'm just confused about what those are and how they work.

1
2
3
4
5
6
7
8
9
10
11

public:

	Player(std::string name);

	Player();

	Player(const Player &p);

	Player &operator=(const Player &p);
You can think of them as class functions with funny syntax.

Player(const Player &p);
This function is called when you create a new Player object by passing the constructor an existing one:
1
2
Player oldplayer;
Player newplayer(oldplayer); // Player(const Player &p) is called here 
We call this function the copy constructor.

Player &operator=(const Player &p);
This function is called like this:
1
2
3
Player oldplayer;
Player newplayer;
newplayer = oldPlayer; // Player &operator=(const Player &p) is called here 
We call this function the assignment operator.

Is the "&operator=" overriding the p?

No idea what you're talking about. It's a class function called using = , the input parameter is a reference to a Player object, the returned value is a reference to a Player object.
Last edited on
Is the "&operator=" overriding the p?

The Player& return value should be a reference to the left-hand-side argument. p is not modified, it is const. Not sure if that answers your question any more than Repeater, though.

For example, when you do

1
2
3
const int a = 42;
int b;
int c = b = a;


int c = b = a; is evaluated as int c = (b = a); and the return value is then a reference to the left-hand side (i.e. the object that was assigned a value), which is b.
Last edited on
Topic archived. No new replies allowed.