Leviathan
Leviathan

Reputation: 23

Unable to change private variable's content

main.cpp :

#include <iostream>
#include <string>
#include "Players.h"
using namespace std;

int main ()
{
    cout << "**** Welcome to Leviathan's first TicTacToe Game! ****\n\n";
    Players getNamesobject;
    Players printNamesobject;
    getNamesobject.getPlayersNames();
    printNamesobject.printPlayersNames();

}

Players.h:

#ifndef PLAYERS_H
#define PLAYERS_H


class Players
{
    public:
        void getPlayersNames();
        void printPlayersNames();
    private:
        std::string _player1Name;
        std::string _player2Name;
};

#endif // PLAYERS_H

Players.cpp :

#include <iostream>
#include <string>
#include "Players.h"
using namespace std;

void Players::getPlayersNames()
{
    string p1,p2;
    cout << "Enter player 1 name : ";
    cin >> p1;
    cout << "\nEnter player 2 name : ";
    cin >> p2;
    _player1Name = p1;
    _player2Name = p2;
}

void Players::printPlayersNames()
{
    cout << "Alright " << _player1Name << " and " << _player2Name <<", the game has begun!\n\n";
}

When i run this, and enter two names, the _player1Name and _player2Name variables don't get changed. I've tried setting them a string manually and they get printed normally. Can anyone explain what's wrong here? It seems like getPlayerNames function can't change the private variables?

Upvotes: 2

Views: 436

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

It's because you have two different objects!

One that you set the member variables in (through the getPlayersNames function), and another unrelated object you use to print a different set of variables.

You should have a single object, and call getPlayersNames and printPlayersNames on that single object. Like

Players playersObject;
playersObject.getPlayersNames();
playersObject.printPlayersNames();

Each instance of the Players object you create will have its own set of member variables that are tied to that single object, member variables are not shared between objects (unless you make them static).

Upvotes: 7

Related Questions