Techniques of Initializing a Class
There are various techniques used to initialize a class: initializing individual members or initializing the class as a whole.
To initialize a member of a class, access it and assign it an appropriate value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | #include <iostream> #include <string> using namespace std; class ShoeBox { public: double Length, Width, Height; string Color; float ShoeSize; private: }; int main() { ShoeBox Shake; double Volume; // Initializing each member of the class Shake.Length = 12.55; Shake.Width = 6.32; Shake.Height = 8.74; Shake.Color = "Yellow Stone"; Shake.ShoeSize = 10.50; Volume = Shake.Length * Shake.Width * Shake.Height; // Display the characteristics of the shoe box cout << "Characteristics of this shoe box"; cout << "\n\tLength = " << Shake.Length << "\n\tWidth = " << Shake.Width << "\n\tHeight = " << Shake.Height << "\n\tVolume = " << Volume << "\n\tColor = " << Shake.Color << "\n\tSize = " << Shake.ShoeSize << "\n\n"; return 0; } |
This time, the program would render a reasonable result.
You can also initialize an object as a variable. This time, type the name of the variable followed by the assignment operator, followed by the desired values of the variables listed between an opening and a closing curly brackets; each value is separated with a comma. The first rule you must keep in mind is that the list of variables must follow the order of the declared members of the class. The second rule you must observe is that none of the members of the class must be another class. In the following example, one of the members of the class is another class, namely a string. Because of the way a variable of the class is declared, the program would not compile:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | #include <iostream> #include <string> using namespace std; class ShoeBox { public: double Length, Width, Height; string Color; float ShoeSize; private: }; int main() { // Declaring and initializing the class as a variable ShoeBox LadyShake = { 12.55, 6.32, 8.74, "Yellow Stone", 10.50 }; Double Volume = LadyShake.Length * LadyShake.Width * LadyShake.Height; // Display the characteristics of the shoe box cout << "Characteristics of this shoe box"; cout << "\n\tLength = " << LadyShake.Length << "\n\tWidth = " << LadyShake.Width << "\n\tHeight = " << LadyShake.Height << "\n\tVolume = " << Volume << "\n\tColor = " << LadyShake.Color << "\n\tSize = " << LadyShake.ShoeSize << "\n\n"; return 0; } |