private variables in functions

without getting too into it, i need to access a private variable to use that number in a calculation. i have a function to return it, my question becomes if I call
1
2
3
4
5
int PVreturn()
{
return privateVariableName
};


is this something that I can drop into a math equation?
example:

1
2
3
4
5
6
int PvMaths()
{
int newvariable
newvariable = PVreturn() + 6
};


if not what's the best way I could do that?
Last edited on
If they are in two different classes then a getter should be fine if not you should just access the private directly. Or, if it is inherited then protected would be best.
giblit wrote:
if it is inherited then protected would be best.

Not necessarily. You might want to protect your members from accidental modifications in subclasses just as you do with other classes.
The function is in an inherited class, the variable is in the base class as a private variable.

and thats exactly what i'm hoping for by keeping it private, that I won't accidentally modify it somewhere.
long story short I'm writing a program to simulate a bank account / atm, and this formula is going to be used to calculate the interest rate of the bank account.

however to do so the account balance variable is in a publicly accessed class as a private variable. I have a public function just like above that does a return on the variable but I'm wondering if that's enough? It doesn't seem to work when I use it in another program i'm using just to test functions

also I haven't learned about protected yet in my class, so I don't know if I can do that

I don't really know what I'm doing, so in a test function to see if I could I did this. it built and ran successfully but returned math as a value of 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <iomanip>

using namespace std;
int math;
int value = 10;
int balance = 100;

int returnmath()
{
return value;
};

int main ()
{ 


	math == returnmath() * balance;
		cout << math << endl;
	

	system ("pause");
}


edit: sorry. i'm an idiot with the ==.
Last edited on
Use BaseClass::getFunction() to get the private data from the base class while in the derived class.
e.g

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class BaseClass
{
public:
   int getFunction()
   {
      return value;
   }
private:
   int value;
};

class DerivedClass : public BaseClass
{
 public:
   int someFunction()
  {
       return BaseClass::getFunction() + someOtherStuff();
  }
};


Accessing the private value member of the base class via the
BaseClass::getFunction() call keeps the private data member in the base class free from being corrupted later and of course is accessible by rules governing inheritance hierarchies.

Topic archived. No new replies allowed.