6.096 Problem Set

[Pages:15]6.096 Problem Set 3

1 Additional Material

1.1 Arrays of class objects

An array of class objects is similar to an array of some other data type. To create an array of Points, we write

Point parray[4];

To access the object at position i of the array, we write

parray[i]

and to call a method on that object method, we write

parray[i].methodName(arg1 , arg2 , ...);

To initialize an array of objects whose values are known at compile time, we can write

Point parray[4] = {Point(0,1), Point(1,2), Point(3,5), Point(8,13)};

We can also allocate an array of objects dynamically using the new operator (this implicitly calls the default constructor of each new Point):

Point* parray = new Point[4];

1.2 Static members and variables

Static data members of a class are also known as "class variables," because there is only one unique value for all the objects of that class. Their content is not different from one object of this class to another.

For example, it may be used for a variable within a class that can contain a counter with the number of objects of the class that are currently allocated, as in the following example:

1 #include 2 3 using namespace std; 4 5 class CDummy 6 {

1

7 public :

8

static int n ;

9

CDummy () { ++ n ; }

10

~CDummy() { --n; }

11 };

12

13 int CDummy :: n = 0;

14

15 int main ()

16 {

17

CDummy a;

18

CDummy b[5];

19

CDummy* c = new CDummy;

20

cout ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download