Creating global instances or objects of structures
A technique to create instances of a structure which can be used by many functions,
Learning Objectives
- Learning to declare global objects/instances of a structure along with the structure definition itself.
Source Code
|
Run Output
Code Understanding
void setApple(void); //this function declaration is used to set values in apple object of struct
struct Fruit //This a struct which define some variables related to Fruit.
{
int weight; //An integer variable that will contain the fruit weight
float price; //A float variable that will contain the price of the fruit.
}apple,banana; //These two are global instances/objects declared along with the structure itself.
int main() {
banana.weight=45; banana.price=3.25;
These variables of object banana are set in the main routine.
cout<<“FruitttWeighttPrice”<<endl; cout<<“—————————–“<<endl;
This will print as heading line of information we shall print further.
cout<<“Bananatt” <<banana.weight<<“t”<<banana.price<<endl;
This line prints the details picked from the banana object.
setApple();
This function set the values in the apple object. The apple object is outside main() and setApple() functions still they can be accessed anywhere.
cout<<“Applett” <<apple.weight<<“t”<<apple.price<<endl;
Value of apple object are printed here.
void setApple() {apple.weight=55; apple.price=10.50;}
This function sets the variables in the apple object which is a global object. If object would have been declared inside the main routine these variables will not accessible.
Notes
- Other than declaring global objects along with structure syntax near the ending braces, the global objects can also be declared in the global area above the main routine as follows –
Fruit apple, banana;
int main()
{ ………… }
Common Errors
- Some student declare global objects after the semicolon of the structure as follows –
struct Name{…};a,b
This is incorrect. This should be –
struct Name { … }a,b;
Suggested Filename(s): stru-global-obj.cpp, strucglo.cpp
sunmitra| Created: 18-Jan-2018 | Updated: 2-Feb-2018|