Accessing Private Variables Within Class

Quick question on private variables. If I want to access a variable from within the class, how does that look? For example, if my header file had:

1
2
3
4
5
6
7
8
9
10
class someClass
{
   private:
      int num;
   public:
   int calculate(int userIn);
.
.
.
}


and I had a separate source file that wanted to use num in a calculation, would i have to pass it in some way? or is it like setters and getters where it'd just be like:

1
2
3
4
5
6
7
#include "someClass.hpp"

int someClass::calculate(userInput)
{
   int newNum;
   newNum=userInput+num;
}
add a friend class clFriend; to the class of which private variables you want to reach.

1
2
3
4
5
6
7
8
9
10
11
12
13
class class1{
friend class class2;
private:
	double privateStuff;
};

class class2{
public:
	double getPrivateValues( class1 * cl1 ){
	cl1 = new class1;
	return cl1->privateStuff;
	}
};


this should do it.
Hello stephcat5,

peytuk has a solution, but I believe it is unnecessary. As I understand it a member function of a class has access to all "private" variables in the class.

Your code would work if you did it right:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class someClass
{
   private:
      int num;
   public:
   int calculate(int userIn);
.
.
.
}

	

#include "someClass.hpp"

int someClass::calculate(int userIn)
{
   int newNum;
   newNum=userIn+num;
}

It helps when the forward declaration matches the function definition.

You can always change the name used in the function definition if you like, but I find it easier to have the prototype and function definition match.

For now this is untested, but should work.

Hope that helps,

Andy
when you call a member function, the object is passed as a hidden argument, the this pointer
so
1
2
3
4
5
6
someClass foo;
foo.calculate(42);
//will call
int someClass::calculate(int userInput){
   this->num //refers to foo.num
}
this-> may be omitted, so you can simply write num


@peytuk: your code is horrendous
you dismiss the parameter passed
you create a new object dynamically
you leak that memory
and don't even solve the original problem, as you are not accessing a particular object.
Topic archived. No new replies allowed.