Home Previous Next

CSC100 :: Lecture Note :: Week 14
{GDT::Bits:: Time  |  Weather  |  Populations  |  Special Dates}

Overview
Assignment(s):
Code: factorial.cpp (recursion) | pointer0.cpp | StructStudent.cpp | Dog.cpp (class)

Pointers

A pointer is a variable whose value is an address of another variable.

• pointers are referred to as derived data types
• a pointer is a variable (it has a name, and it points to a particular type of data)
• the amount of space allocated for a pointer variable is typically the size allocated for an `int`
• pointer variables are assigned address values obtained using the address-of operator `&`
• local pointer variables are uninitialized
Defining and Initializing Pointer Variables
When defining a variable, prefixing the variable's name with an asterik `*` causes the variable to be a pointer.

```   int* iptr;   /*define variable iptr that will point to an int variable*/
float * fptr; /*define variable fptr that will point to a float variable*/
char *cptr;  /*define variable cptr that will point to a character*/
int i, j;
float f;
char c;

iptr = &i;  /*assign the address-of variable 'i' to iptr*/
fptr = &f;  /*assign the address-of variable 'f' to fptr*/
cptr = &c;  /*assign the address-of variable 'c' to cptr*/
int* iptr2 = &j; /*define and initialize an int pointer*/
iptr = iptr2;  /*now iptr points to the variable 'j'*/

note:  Placement of the  *  when defining a pointer variable is
a matter of style -- I like to place the  *  next to the
data type, but others prefer to place it next to the
variable name.  Placing it next to the data type does
require caution when multiple variables are defined on
the same declaration statement.  Example:

int* ip1, ip2;
// ip1  is a pointer to an  int  , but  ip2  is a
regular  int

int* ip1, *ip2;
// ip1  and  ip2  are both pointers to an  int
```

The address-of operator only applies to objects in memory: variables and array elements.

Locally defined non-static pointers, unless explicitly initialized, are garbage and using them without initialization can cause a program to execute incorrectly (or abort).

Global and statically defined pointers are initialized to the `NULL` pointer.

Accessing Data Using Pointers

The unary operator `*` is the indirection or dereferencing operator; when applied to a pointer, it accesses the object the pointer points to.

```   int i = 200;
int* iptr = &i;

cout << *iptr;    /*prints 200 -- the value of 'i' which is the object
iptr points to*/
```
Pointers and Function Arguments

Since C passes arguments to functions by value, there is no way for the called function to alter a variable in the calling function. A way to obtain the desired effect is for the calling program to pass pointers to the values to be changed.

```   void swap(int*, int*);

int i, j;

swap(&i, &j);

void swap(int* a, int* b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
```

Using pointers is similar to using reference variables; however, reference variables are part of C++ and they are not part of C.

Advantage of using reference variables over pointers.

• cleaner syntax

Introduction to Pointers and Arrays

There is a strong relationship between pointers and arrays.

When an array name is used by itself, it evaluates to a constant pointer to the first element of the array.

Everywhere you use `arrayName[index]` you can use `*(ptr + index)` (assuming `ptr` points to some part of the array).

```   int scores[10];

scores[0] = 2;      // or  *scores = 2
scores[1] = 3;      // or  *(scores + 1) = 3
*(scores + 2) = 5;  // or  scores[2] = 5
```

Structures

A `struct` (structure) is an aggregate of elements of arbitary types. (An array is an aggregate of elements of the same type.)

An example of a structure.

```   struct Grade {
float points;
char letter;
};  /* the semicolon after the  }  is required */
```

Structures are sometimes referred to as records.

A `struct` consists of zero or more fields (or members).

• variables of type `struct` can be defined and declared exactly as other variables
```     struct Grade grade1;  /*keyword  struct  required in C*/
```
• it is possible to define variables immediately after declaring a structure
• ```     enum { STREET_LEN = 32, CITY_LEN = 32, STATE_LEN = 4 };

char street[STREET_LEN];
char city[CITY_LEN];
char state[STATE_LEN];
long zipcode;
short int zipcodePlus4;
};

#define LEN_NAME 64

struct Person {
char name[LEN_NAME];
int age;
char* datafile;
} bob, ted, carol, alice;

note: structure members can contain arrays, pointers, and
other structures
```
• individual members are accessed using the member-of (or dot) operator
```     grade1.points = 99.3;

bob.age = 21;
```
• notation used to initialize arrays can also be used to initialize structure variables (initialization can occur only at the time of definition)
```     struct Grade grade2 = { 83.7, 'B' };
struct Grade grades[] = { 99.3, 'A', 45.7, 'F', 76.2, 'C' };
/* compiler creates a 3 element array */
/* elements 1-4 are initialized to 0 */
/*! grade2 = { 99.1, 'A' };   // illegal */

```
• structure objects are often accessed through pointers using the `->` operator
```     printGrade(&grade1);

g->points = 88.0;
g->letter = 'B';
}

the  ->  operator was added to the language for convience;
when  p  is a pointer,  p->m  equivalent to  (*p).m

note:  when making a function call, passing a pointer to a
structure variable is more efficient than passing by value
```
• operations such as `==` and `!=` are not defined on structure variables
```     if (grade1 == grade2)  /* is not legal */
```
• one structure variable can be copied to another structure variable using the assignment operator, but only if they are of the same type (e.g. `grade1 = grade2`)
• the size of a `struct` is not necessarily the sum of the sizes of its members; always use the ``` sizeof()``` operator (for efficiency reason, the compiler may want integral values to begin on an even word boundary, etc. -- usually this behavior can be altered by using `#pragma` compiler directives)
• the `offsetof` macro is used to determine the offset in bytes of a member from the start of the structure that contains it
```     #include <stddef.h>

struct xyz { int a, b, c; };

size_t offset = offsetof(struct xyz, b);
/* on a 4-byte int system,  offset  will probably be equal to 4 */
```
• a `struct` is a simple form of a `class`
• the name of a type becomes available for use immediately after it has has been encountered
```     struct Link {
};
```
• it is not possible to declare new objects of a structure type until the complete declaration has been seen
```     struct Node {
Node n; /*illegal -- recursive definition*/
};

The following is allowed.

struct List;   /*this is an incomplete type */

struct List* listItem;
};

struct List {
};
```
• two structures are different types even when they have the same members
• it is possible to declare a struct and a non-struct with the same name in the same scope (be careful in C++)
```     struct abc { ... };
int abc;
struct def { ..., int def, ... } def;

def: def.def = 100;
```

Introduction to Classes

We could spend weeks on the topic of class design. When developing a large program or a system (i.e. a collection of programs that work together to provide a specific application), class design is one of the most critical steps in the software development cycle.

In this course sequence we get an introduction to what classes are and how to create and use them using the C++ programming language.

A class is a blueprint from which objects are instantiated (i.e. created). [Classes are also referred to as models or patterns or templates -- although you should avoid using the term template.]

Objects are instances of a class. Objects have memory allocated for them and are usually considered system resources. Memory is allocated from the heap (or free store).]

Object-oriented programs require you to think of programs as being a collection of objects that work together to provide an application.

Object-oriented design is a software design methodology that models the characteristics of abstract or real objects using classes and objects.

The class declares data the defines the state that objects of the class can take on, and methods that define the behavior that the objects can exhibit or be subjected to.

An object is a software "capsule" containing variables and related methods. The values of the variables define an object's state, and the methods define the behavior an object can be subjected to.

A method is a function defined in a class. C++ classes can contain instance methods and class methods. Class methods are defined to be `static`.

The `public` methods of a class defines the API or Application Programmer Interface for the class.

The data that is specific to a particular instance of an object is called instance data. Ideally, clients should not have to beware of the instance data in order to use objects of your class.

A class declaration has the following syntax.

```   class SomeClassName {
private:
0_or_more_data_members;
0_or_more_method_members;
public:
0_or_more_data_members;
0_or_more_method_members;
};

// class, private and public are C++ keywords
```

Once an object instantiated (created), messages can be sent to it as follows:

```   SomeClassName objectVariable;

objectVariable.methodName(...)
```

Where `objectVariable` is the name of a variable that stores the data contained within an object, and `methodName` is the name of a method defined in the class `SomeClassName`.

`objectVariable` is referred to as the recipient object. Or here it described as: `methodName()` is invoked on behalf of `objectVariable`. Or the `methodName` message is sent to `objectVariable`.

The `methodName()` method is called. If arguments are supplied, then the value of those arguments are passed to the method (the method receives them as parameters). Implicitly, every method that is invoked on behalf of an object (referred to as an instance method), receives a parameter that has the name `this`. `this` is an `objectVariable` that points to the recipient object.

[class example: Time.cpp | Dog.cpp]

When defining instance variables, you should use `private` as much as possible. Private instance data members can be accessed only by the methods defined in the class.

Making data private provides the following benefits:

• controls who can and cannot access the data
• prevents the data from being set to invalid values
• allows you to change the underlying representation of the data

By convention, mutator methods begin with the word `set`. In many cases, `set` is followed with the name of instance variable.

When you want the client to be able to access private data, then an accessor or getter method is provided.

By convention, accessor methods begin with the word `get` which it then often following by the name of the instance variable.

Accessor methods are often covert the value of instance variables from their internal representation to types that are usable by the client.

Accessor methods are usually short methods.

Home Previous Next