Declaring a Class
After defining a class, you can declare it as a variable using the same syntax we have used for any other variable. A class is declared using its name followed by a name for the defined variable and ending with a semi-colon. For example, our ShoeBox class can be declared as follows:
1 | ShoeBox Shake; |
When an object has been declared, you can access any of its members using the member access operator “.”. First, type the name of the object variable, followed by a period, followed by the name of the member you want to access. For example, to access the member Length of the above class, you would write:
Shake.Length;
Using this syntax, you can display the value of a class member:
cout << Shake.Length;
or you can request its value from the user, using the cin operator. Here is an example:
cin >> Shake.Lengh;
Using the
cout
extractor to display the values of the object members, our program could be as follows:
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 | #include <iostream> #include <string> using namespace std; c lass ShoeBox { public: double Length, Width, Height; string Color; private: float ShoeSize; }; int main() { ShoeBox Shake; // 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 = " << Shake.Length * Shake.Width * Shake.Height << "\n\tColor = " << Shake.Color << "\n\tSize = " << Shake.ShoeSize << "\n\n"; return 0; } |
At this time, because of trying to access a private member, the program would produce the following error
[C++ Error] Unit1.cpp(30): E2247 ‘ShoeBox::TShoeSize’ is not accessible
Even if you change the ShoeSize member access from private to public, the program would render unpredictable results because the members have not been given appropriate values:
Characteristics of this shoe box Length = 0 Width = 1.79571e-307 Height = 4.17266e-315 Volume = 0 Color = Size = 3.58732e-43
Press any key to continue…