Hi,
Suppose I have a class TClass. Now, I need a variable x of type TSomeType within that class to be passed to functions. However, the functions cannot "know" what type the class is (in this case, TClass) because they may receive variables from multiple different classes. Also I want x to be modifiable by the member functions of TClass, but not by any functions which x may be passed to.
So for example, I cannot do something like this:
The reason I can't do that is because then Function1 would have to "know" the type TClass. Also I can't do something like this:Code:class TClass {
private:
TSomeType x;
...
public:
TSomeType Getx() {return x;};
...
};
void Function1(TClass *c) {
TSomeType x1;
x1 = c->Getx();
...
}
int main() {
TClass class;
Function1(&class);
...
}
because then Function2 could theoretically modify the value of y. Now I know that I could replace "TSomeType *y" with "const TSomeType *y" and that this would fix it in this particular case, but another function which was maybe written by someone else could leave out this "const" qualifier.Code:class TClass {
...
public:
TSomeType x;
};
void Function2(TSomeType *y) {
TSomeType y1 = &y;
...
}
int main() {
TClass c;
Function2(&(c->x));
...
}
So I suppose what I am asking is this: is there a way to make a class member so that it can only be modified by the class member functions themselves (like a private member) but that a pointer to it can still be passed to another function as a parameter if the parameter name is "const" qualified in the prototype (like a public member)?
I have seen the word "const" used in front of variables rather than functions inside of a class definition, and am not sure if this will do what I need it to; in fact I am not sure of what THAT syntax means at all.
One other thing. There is a fairly obvious way around this situation, but it's quite ugly and I'm sure that there would be a better way. It's to do this:
and then simply make sure you set y equal to x after every class member function return which modifies x. However as I just said this is very ugly and perhaps even inefficient.Code:class TClass {
private:
TSomeType x;
...
public:
TSomeType y;
...
};
void Function3(TSomeType *z)
{
TSomeType z1 = &z;
...
}
int main()
{
TClass c;
Function3(&(c->y));
...
}