Yahboysurge
Yahboysurge

Reputation: 73

Pointer changes value after storing it in an object (C++)

I notice (to me) weird behavior. If I initialize a DerivedClass and pass a pointer of another class (player) to it, then it receives the right pointer value. However, if I then try to use that pointer, later on in check_pointer_of_player(), the value changed. I do not understand this behavior, and I would like to know how I can alternatively achieve the goal: use functions of player within the DerivedClass.

class DerivedClass : public ParentClass {
    protected:
        Player* player;
    public:
        DerivedClass(Coord p, Player* player) : ParentClass(p) {
            std::cout << "During intialization the pointer value is: " << player << "\n";
            player = player;
        }

        void check_pointer_of_player() {
            std::cout << "Now the pointer value is: " << player << "\n";
        }

As I wrote, during initialization the pointer value is correct, but later when I call this class' function check_pointer_value() it returns a different value. Below is the output visible.

During intialization the pointer value is: 0x7f908f558710

Now the pointer value is: 0x7fff41140004

How do I still achieve my goal.

Upvotes: 0

Views: 487

Answers (1)

cigien
cigien

Reputation: 60238

Inside the body of the constructor, the parameter player is shadowing the member player, so you are not actually assigning the parameter to the member. This is why only the constructor shows the correct value of player when you print it out.

You can disambiguate like this:

DerivedClass(Coord p, Player* player) : ParentClass(p) {
    std::cout << "During intialization the pointer value is: " << player << "\n";
    this->player = player;
}

Or just give the parameter a different name:

DerivedClass(Coord p, Player* player_param) : ParentClass(p) {
    std::cout << "During intialization the pointer value is: " << player << "\n";
    player = player_param;
}

The best option would be to use a member initializer list, where the names can actually be the same, so you could do:

DerivedClass(Coord p, Player* player) : ParentClass(p), player(player) {
    std::cout << "During intialization the pointer value is: " << player << "\n";
}

Upvotes: 3

Related Questions