-3
void User :: buyApples(){   
while(1){
        cout<<"How many do you want to buy? Press 0 to quit.";cin>>qq;

        if(qq==0)
            return ;

        if(qq<= f.getnumofApples()){
            if(salary>=(qq*200)){
                invofApples+=qq;
                salary-=(qq*200);
                showsalary();       
            }
            else{
                cout<<"Not enough money"<<endl;
                void homescreen();
            }
        }
        else{
            cout<<"There's not enough Apples in Stock"<<endl;
            continue;
        }
    }
}

This code is a market with qq being input using cin.

I can change the salary and private variables that are in the User class.

But I also need to change the private variables that are in the fruit class with int numofApples. How can I change the numofApples?

I can't seem to change the variable from the User class. When I tried to change it from the fruit class, the qq doesn't carry over. What do I do?

duffymo
  • 305,152
  • 44
  • 369
  • 561
Ash Lee
  • 1
  • 1
  • 1
    That's the whole point of `private` variables - to disallow modification of those from outside of the class. If you want to change the values of those - create public methods for that, or make those variables as public. – Algirdas Preidžius Jul 19 '16 at 11:58

4 Answers4

3

If you want to access a private variable from another class you should implement a public method to do so in that class, a get/set method for example.

With this you will preserve the visibility of the variable

sendra
  • 658
  • 1
  • 9
  • 21
1

You can allow the User class to access the private variables of the Fruit class by declaring it as a friend of Fruit, i.e.

class Fruit {
    friend class User;

    /* Rest of class */
}

The question is, is this really what you want? Private variables are generally for things that should not be altered by other classes.

James Elderfield
  • 2,389
  • 1
  • 34
  • 39
1

No one can answer unless you post your User and Fruit classes.

Before you do, think about what object oriented programming is about: encapsulation of data and behavior into software components. The idea behind private variables in a class is that you need to provide public methods to update them. If you don't provide methods, you imply that you don't want the values to be changed outside the class.

Add public methods to the class that owns the variable you want to change. Call those methods in your code where you want to update them.

duffymo
  • 305,152
  • 44
  • 369
  • 561
1

The purpose of private members is to keep them from being accessed externally when you don't want them to be. If you want to allow access, then you must provide a way for the user to set the value. Here is an example of a setter method on the Fruit class that could allow the user to set the number of apples.

void Fruit::setNumberOfApples(int newNumApples) 
{ 
    numofApples = newNumApples; 
}
leetibbett
  • 843
  • 4
  • 16