Головна

Constructors

  1. Constructors

Constructors are the methods of a class that define what actions to take when creating an object. A C ++ class can have multiple constructors. This allows variation in object instantiation since different numbers and types of parameters can exist in each constructor. The following listing is a modified version of the C ++ BankAccount class. This modified version includes an additional constructor.

 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: class BankAccount {private: double sum; string name; public: BankAccount (string nm): name (nm), sum (0) {} BankAccount (string nm, double bal): name (nm), sum (bal) {} double balance () {return sum;} void deposit (double amount) {sum + = amount;} void withdraw (double amount) {sum - = amount;} string getName () {return name;}};
 Listing 3 Initializer lists and multiple constructors

The use of initializer lists in constructors is the preferred way to specify initial values ??for class data members. Initializer lists are comma-separated variable initializations that appear prior to the body of a constructor. An example of initializer lists appears in Listing 3. Everything in line 8 following the colon and preceding the empty curly-braces comprises the initializer list. This initializer list sets the initial value of the private data member name equal to the value of parameter nm. It also sets the initial value of the data member sum equal to zero.

Listing 4 demonstrates instantiation of class BankAccount.

 1: 2: 3: 4: 5: BankAccount account1 ("checking"); BankAccount account2 ("savings", 200); account2.withdraw (100); account1.deposit (100);
 Listing 4 Object instantiation

C ++ instantiates an object when the line of code containing the object declaration executes. Object instantiation involves the execution of a class constructor. Listing 4 declares two different BankAccount objects. Instantiation occurs when the code contained in lines 1 and 2 executes.

Створення нових імен типів даних. | Declaration vs. Definition


Assessments | Strings | Creating New Data Type Names | Constructors | Declaration vs. Definition | Streams | Using the Standard Streams | File Input and Output | Streams | Using the Standard Streams |

© 2016-2022  um.co.ua - учбові матеріали та реферати