|
|
We will discuss this next....
|
An access qualifier determines which functions can read/write a variable or can invoke a function
class Matrix3x3
{
public:
float A[3][3];
...
}
|
|
class myClass
{
public:
int x; // Public variables
void f1(int a)
{
x = a; // Access public member variable
// (It's actually: this->x = a;
}
};
class yourClass
{
public:
void f1(myClass & p, int a)
{
p.x = a; // Access public member variable
}
};
int main(int argc, char ** argv)
{
myClass jam;
yourClass butter;
jam.x = 1234;
butter.f1(jam, 4444);
jam.f1(7777);
}
|
|
class myClass
{
private:
int x; // Private variable
void f1(int a) // Private function
{
x = a; // ALLOW access to private variable
// (It's actually: this->x = a;
}
};
class yourClass
{
public:
void f1(myClass & p, int a)
{
p.x = a; // ERROR: NO access to private variable
}
};
int main(int argc, char ** argv)
{
myClass jam;
jam.x = 1234; // ERROR: NO access to private variable
butter.f1(jam, 4444);
jam.f1(7777);
}
|
void f1(myClass & p, int a)
{
p.x = a; // ERROR: NO access to private variable
}
Error: x is not accessible from yourClass::f1(myClass&, int).
|
 
class Matrix3x3
{
private:
double A[3][3];
public:
int init(double m[3][3]) // Check for symmetry
{
if ( ! isSymmetric(m) )
{
cout << "Input matrix is NOT symmetric" << endl;
// Initialize matrix to a "dummy" matrix
for (i = 0; i < 3; i = i + 1)
for (j = 0; j < 3; j = j + 1)
A[i][j] = 0;
return(0); // Error indication
}
// Initialize matrix with input
for ( i = 0; i < 3; i = i + 1 )
for ( j = 0; j < 3; j = j + 1 )
A[i][j] = m[i][j];
return(1); // OK
}
...
}
|
int main(int argc, char *argv[])
{
Matrix3x3 A, B, C;
A.A[0][0] = 1.0; A.A[0][1] = 0.0; A.A[0][2] = 0.0; // NOT allowed !!!
A.A[1][0] = 1.0; A.A[1][1] = 1.0; A.A[1][2] = 1.0; // NOT allowed !!!
A.A[2][0] = 1.0; A.A[2][1] = 0.0; A.A[2][2] = 0.0; // NOT allowed !!!
...
}
|
int main(int argc, char *argv[])
{
Matrix3x3 A, B, C;
double p[3][3];
p[0][0] = 1.0; p[0][1] = 0.0; p[0][2] = 1.0;
p[1][0] = 0.0; p[1][1] = 1.0; p[1][2] = 1.0;
p[2][0] = 1.0; p[2][1] = 1.0; p[2][2] = 0.0;
if ( A.init(p) == 0 )
{
cout << "Input error, exiting..." << endl;
exit(1);
}
...
}
|
| You have more control on WHAT operations will be allowed on member variables that are private |
The example above showed:
|
A good hacker will be able to access the private variables in a class
|
class myMatrix3x3
{
public:
double A[3][3];
}
class Matrix3x3
{
private:
double A[3][3];
...
}
int main(int argc, char *argv[])
{
Matrix3x3 A, B, C;
myMatrix3x3 *m;
m = &A;
m->A[0][0] = 1.0; m->A[0][1] = 0.0; m->A[0][2] = 1.0;
m->A[1][0] = 0.0; m->A[1][1] = 1.0; m->A[1][2] = 1.0;
m->A[2][0] = 1.0; m->A[2][1] = 1.0; m->A[2][2] = 0.0;
}
|