structs, which are basically classes with all
members public:
struct X
{
int i;
int j;
};
However, there are no member functions in C. As a result, all methods
(operations) must be performed by subroutines. For example, in order to
initialize an object of struct X type, we can define the following
subroutine:
void X_init(struct X *pX)
{
pX->i = 0;
pX->j = 0;
}
In a program, we can have the following code to define a struct X
object, and initialize it:
{
struct X myX;
// ...
X_init(&myX);
}
This works, but it is not that object-oriented. In C++, however, we have
member functions. Each member function can access all the data members
(as well as other member functions) of the same class. In other words, we
can define a equivalent class (as struct X) as follows:
class Y
{
private:
int i,j;
public:
void init(void);
};
init in this case is member function. There is no need to say
Y_init because it is a member function of the class Y. The
definition of the function is as follows:
void Y::init(void)
{
i = 0;
j = 0;
}
Note the main difference between Y::init and X_init is that
there is no pointer dereference in Y::init! In fact, Y::init
has no parameter. The following sample code illustrates how to use this
member function.
{
Y myY;
// ...
myY.init();
}
Instead of specifying myY as a parameter to Y::init, init
is accessed as a member (function) of myY.
So how does init knows that it is accessing the members of myY?
Copyright © 2006-09-12 by Tak Auyeung