Page 261 - Introduction to Microcontrollers Architecture, Programming, and Interfacing of The Motorola 68HC12
P. 261
238 Chapter 8 Programming in C and C++
The object's data members, Error, Bottom, Top, and Ptr, are stored in mernory
just the way a global struct is stored. Suppose s is a stack object as described above,
and Sptr is a pointer to a stack object. If a data member could be accessed in main, as
in i = s.Error or i = Sptr->Error (we see later that it can't be accessed from
main), the data member is accessed by using a predetermined offset from the base of the
object exactly as a member of a C struct is accessed. Function members can be called
using notation similar to that used to access data in a struct; s.pushf 1) calls the
push function member of s to push 1 onto S's stack. The "s. " in front of the
function member is rather like a first actual parameter, as in push(s, 1), but can be
used to select the function member to be run, as we will see later, so it appears before
the function.
The class's constructor is executed before the main procedure is executed, to
initialize the values of data members of the object. This declaration s (10) passes actual
parameter 10 to the constructor, which uses it, as formal parameter i, to allocate 10
bytes for the stack. The stack is stored in a buffer assigned by the allocate routine.
Similarly a local object of a class can be declared and then used as shown below;
void main() { int i; Cstack S(10);
S.push(l); i = S.pull();
}
The data members Error, Bottom, Top, and Ptr, are stored on the hardware stack,
and the constructor is called just after main is entered to initialize these data members; it
then calls allocate to find room for the stack. The function members are called the
same way as in the first example when the object was declared globally.
Alternatively, a pointer Sptr to an object can be declared globally or locally; then
an object is set up and then used as shown below.
void main{) { Cstack * Sptr; int i;
Sptr = new Cstack (20);
Sptr ->push(l); i = Sptr ->pull();
}
In the first line, Sptr, a pointer to an object of class stack, is declared here as a local
variable. (Alternatively it could have been declared as a global variable pointer.) The
expression Sptr = new Cstack (20); is put anywhere before the object is used. This
is called blessing the object. The allocator and then the constructor are both called by
the operator new. The allocator allocate automatically provides room for the data
members Error, Bottom, Top, and Ptr. The constructor explicitly calls up the
allocate procedure to obtain room for the object's stack itself, and then initializes all the
object's data members. After it is thus blessed, the object can be used in the program. An
alternative way to use a pointer to an object is with a #def ine statement to insert the
asterisk as follows:
#define S (*Sptr)
void main() { int i;
Cstack *Sptr = new Cstack(20);
S.push(l); i = S.pull();
}