Members as Arrays and Arrays of Class Objects


A class may have arrays as data members as well as single data members. For example see bank7.cpp.

C++ permits an array of class objects as well as an array of any other data type. In some cases, it is somewhat easier to initialize the elements of an array of class objects than it is to initialize the elements of a standard data type array. This can happen when the class has an explicit default constructor that initializes the attributes.

As you recall from the previous course in C++, defining an array does not automatically initialize the elements of an array. Therefore the program must go through the chore of initializing the elements or the elements are filled with garbage. That is, an array could be defined by:

image from book

 double transactionAmount[100]; 

image from book

and then each of the transaction amounts must be set to zero. However in C++, just using the definition of the array of objects: transactionAmount[ ] can be sufficient to initializing each of the array's elements to zero by using a constructor. For example if Transaction is a class with a default constructor that initializes the attributes, then the following definition could initialize the array transactionAmount[ ] when it is defined as in the following statement:

image from book

 Transaction transactionAmount[numberTranactions]; 

image from book

See the example: bankaccount.cpp which uses the data in the text file: transactions.txt




Intermediate Business Programming with C++
Intermediate Business Programming with C++
ISBN: 738453099
EAN: N/A
Year: 2007
Pages: 142

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net