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;
}
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.
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.
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.