Initialising structure variables while creating instances
A demonstration of initialisation of values of variables while creating the instances of the structures.
Learning Objectives
- Initialising of structure variables at the time of instance creation.
Source Code
|
Run Output
Code Understanding
struct Monument { char name[50]; int year; };
Structure declaration with two variables char array and int.
Monument m1={“Taj Mahal”,1653};
Monument m2={“Eiffel Tower”,1889};
Monument m3={“Statue of Liberty”,1886};
These are three instance creations with corresponding initialisation. The character array can only be filled while instance creation. It can only be filled later by user input commands or by string copy or memory copy operations.
cout<<“MonumentttYear Completedt”<<endl;
cout<<“————————————–“<<endl;
These are header lines to printed above the output data. Watch out for t (tab) for proper formatting.
cout<<m1.name<<“tt”<<m1.year<<endl;
cout<<m2.name<<“tt”<<m2.year<<endl;
cout<<m3.name<<“t”<<m3.year<<endl;
Three output strings and integer values are printed here with proper tab based formatting. The last line here is longer so only one tab character is used.
Suggested Filename(s): struc-obj-init.cpp,sobjnit.cpp
sunmitra| Created: 19-Jan-2018 | Updated: 2-Feb-2018|